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.
You want the query to look like this:
instead of this:
So try to construct your query with:
where you don’t need to escape the table name, since it’s constructed it in a safe way.