admin管理员组文章数量:1333451
Not sure what I am doing wrong here but I am looking to add a row into db but only if row doesnt already exit with that email address Please see my code below:
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')
);
}
However it seems to be just my passing the if and going straight to else even though email in database is there.
Not sure what I am doing wrong here but I am looking to add a row into db but only if row doesnt already exit with that email address Please see my code below:
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')
);
}
However it seems to be just my passing the if and going straight to else even though email in database is there.
Share Improve this question asked Jun 17, 2020 at 13:59 Louise FinchLouise Finch 211 silver badge3 bronze badges1 Answer
Reset to default 5There are several problems with your function. For example, $tablename
points to a table that does not exist. And you don't need it anyway.
If you are trying to create a new user if that email does not exist then try this:
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 );
}
}
本文标签: functionsCheck if row exists before inserting
版权声明:本文标题:functions - Check if row exists before inserting 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742340205a2456448.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论