I am trying to write function that checks whether an email address is stored in my database or not. I've written the following PHP code::

function check_my_users( $email_address ) {
     global $wpdb;
     $my_table_name = $wpdb->prefix . 'my_users';

     $result = $wpdb->get_var( $wpdb->prepare( 'SELECT email FROM %s WHERE email = %s', $my_table_name, $email_address ) );

     if( $result !== NULL )
         return true;

     return false;

The function always returns false. Additionally, the following query is printed after calling the function: SELECT email FROM 'wp_my_users' WHERE email = '[email protected]'.

Additionally, the following is written to the debug log:

WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''wp_my_users' WHERE email = '[email protected]'' at line 1 for query SELECT email FROM 'wp_my_users' WHERE email = '[email protected]' made by […]

(I added the elipsis)

What is wrong with my function, why do I get that error? To me, everything looks good.

  • This is a SQL syntax question, not a WordPress question. Commented Apr 13, 2014 at 17:06
  • While that is completely true, I wasn't able to know that before getting an answer. It also could have been that there are Wordpress functions that handle the task of my function, for example.
    – Sven
    Commented Apr 13, 2014 at 17:17
  • "You have an error in your SQL syntax seems rather explicit to me... Commented Apr 13, 2014 at 17:40

1 Answer 1


You want the query to look like this:

SELECT email FROM wp_my_users WHERE email = '[email protected]'

instead of this:

SELECT email FROM 'wp_my_users' WHERE email = '[email protected]'

So try to construct your query with:

 $sql = "SELECT email FROM {$my_table_name} WHERE email = %s";
 $result = $wpdb->get_var( $wpdb->prepare( $sql, $email_address ) );

where you don't need to escape the table name, since it's constructed it in a safe way.

  • 1
    Ah that makes sense, of course I only need to prepare user input. Another thing I just noticed is the importance of double quotes. Thank you for your help!
    – Sven
    Commented Apr 13, 2014 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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