我正在尝试编写一个函数来检查电子邮件地址是否存储在我的数据库中。我编写了以下PHP代码:
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;
}
函数始终返回false。此外,调用函数后会打印以下查询:
SELECT email FROM \'wp_my_users\' WHERE email = \'[email protected]\'
.
此外,以下内容会写入调试日志:
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 […]
(我加了省略号)
我的函数有什么问题,为什么会出现这种错误?在我看来,一切都很好。
最合适的回答,由SO网友:birgire 整理而成
您希望查询如下所示:
SELECT email FROM wp_my_users WHERE email = \'[email protected]\'
而不是这样:
SELECT email FROM \'wp_my_users\' WHERE email = \'[email protected]\'
因此,请尝试使用以下内容构造查询:
$sql = "SELECT email FROM {$my_table_name} WHERE email = %s";
$result = $wpdb->get_var( $wpdb->prepare( $sql, $email_address ) );
不需要转义表名,因为它是以安全的方式构造的。