0

I have a problem with quotes with query.

My code:

   $this->table_name= 'table_name';

    $how_much = $this->wpdb->get_var($this->wpdb->prepare("SELECT COUNT(*) FROM {$this->table_name}"));

I have nothing notice or error and site break down.

EDIT

     $how_much= $this->wpdb->get_var($this->wpdb->prepare("SELECT COUNT(*) FROM $this->table_name", $this->table_name));
  • 3
    I think prepare needs 2 arguments, link.... But can I ask you what you need to retrieve? there might be a chance that you don't need to run an SQL query... – Brada Apr 21 at 17:15
  • I need count all records in table and return result. – polyman Apr 21 at 17:21
  • 1
    You use the function totally, wrong... '%s' it's just a string, It's for the first argument and it means something like "Replace this %s with a variable that must be of type string.". More of it here. For the second argument, you need to put the actual variable, that needs to be verify to not contain any vulnerability... If I were you... I wouldn't play with the database... If you need to do that, you must know what you are doing, and what you can expect... What table do you need to check for? It is a custom table or it's an WP one? – Brada Apr 21 at 17:35
  • its custom table – polyman Apr 21 at 17:38
  • I edit code now. – polyman Apr 21 at 17:50
1

Your code should look something like this:

 $this->table_name= 'table_name';

    $how_much = $this->wpdb->get_var("SELECT COUNT(*) FROM $this->table_name");

We don't need to use the prepare method, since this is not meant for table names, more here

And also... as you what are trying to do is going not in a good direction... I don't what to criticize you or anything... But I really suggest you to ask someone who knows better what WordPress can do, about what you need to do, and maybe he will suggest a better approach.

P.S: When you develop something, is good to enable the error/warnings/notices, and have a debugger, to know what's going on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.