不确定我在这里做错了什么,但我希望在db中添加一行,但只有当该行没有使用该电子邮件地址退出时,请参阅下面的代码:
function register_user() {
global $wpdb;
$tablename = $wpdb->prefix."tablename";
$name = $_POST[\'name\'];
$email = $_POST[\'email\'];
$password = $_POST[\'password\'];
$checkIfExists = $wpdb->get_results("SELECT COUNT(*) FROM tablename WHERE email = $email");
$checkRows = mysqli_num_rows($checkIfExists);
if ($checkRows > 0) {
header(\'Location: ../register.php?\');
}
else{
$options = [
\'cost\' => 11,
];
$passwordFromPost = $_POST[\'password\'];
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
$table_name = $wpdb->prefix . "tablename";
$wpdb->insert($table_name, array(
\'name\' => $name,
\'email\' => $email,
\'password\' => $hash
),array(
\'%s\',
\'%s\',
\'%s\')
);
}
尽管数据库中有电子邮件,但似乎只是我通过了if,直接转到了else。
SO网友:shanebp
您的函数有几个问题。例如$tablename
指向不存在的表。而且你也不需要它。如果您正在尝试创建新用户,如果该电子邮件不存在,请尝试以下操作:
function register_user() {
global $wpdb;
$name = $_POST[\'name\'];
$email = $_POST[\'email\'];
$password = $_POST[\'password\'];
$checkIfExists = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE email = \'$email\'");
if ($checkIfExists == NULL) {
$userdata = array(
\'user_login\' => $name,
\'user_email\' => $email,
\'user_pass\' => $password,
);
$user = wp_insert_user( $userdata );
}
}