WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 = 'mail@example.com'.

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 = 'mail@example.com'' at line 1 for query SELECT email FROM 'wp_my_users' WHERE email = 'mail@example.com' made by […]

(I added the elipsis)

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

share|improve this question
This is a SQL syntax question, not a WordPress question. – Chip Bennett Apr 13 '14 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 Apr 13 '14 at 17:17
"You have an error in your SQL syntax seems rather explicit to me... – Chip Bennett Apr 13 '14 at 17:40
up vote 2 down vote accepted

You want the query to look like this:

SELECT email FROM wp_my_users WHERE email = 'mail@example.com'

instead of this:

SELECT email FROM 'wp_my_users' WHERE email = 'mail@example.com'

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.

share|improve this answer
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 Apr 13 '14 at 16:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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