WordPress database error – Error in SQL syntax – I can’t identify any error?

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'.

Read More

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.

Related posts

Leave a Reply

1 comment

  1. 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.