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 badges
Add a comment  | 

1 Answer 1

Reset to default 5

There 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