检查是否已经是用户然后插入数据库 php

Check if already a user then insert into the database php

如果我想插入数据库,我的代码可以工作,但是我检查用户是否已经存在的方法不起作用。

*我认为这个想法是检查是否已经存在具有该用户名的行,如果存在则不要将该用户添加到数据库中,否则

$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];

$result = mysqli_query($mysqli, "SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1){
    echo'User exists';
}else{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);

//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('sss', $username, $email, $password);

if($statement->execute()){
     print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
}else{
     die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}

您混合了 Procedural styleObject oriented style 来执行查询。

使用时,

1) 程序风格

$result = mysqli_query($mysqli, "Your Query");

使用这个,$row_count = mysqli_num_rows($result);

2)面向对象风格

$result = $mysqli->query("Your Query");

用这个,$row_count = $result->num_rows;

所以,根据您的代码,您正在使用面向对象的风格。所以,你需要改变

$result = mysqli_query($mysqli,"SELECT username FROM users WHERE username = '$username'");

$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");

已编辑代码。

$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];

$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1)
{
    echo 'User exists';
}
else
{
    $query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
    $statement = $mysqli->prepare($query);

    //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
    $statement->bind_param('sss', $username, $email, $password);

    if($statement->execute())
    {
         print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
    }
    else
    {
         die('Error : ('. $mysqli->errno .') '. $mysqli->error);
    }
    $statement->close();
}

有关详细信息,请查看此 mysqli_num_rows vs ->num_rows

$db = ("SELECT username FROM userlist WHERE username='$username'");
$query = $conn->query($db);
if(mysqli_fetch_array($query) > 0 ) { //check if there is already an entry for that username
    echo "Username already exists!";
}