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

时间:2015-10-14 15:40:44

标签: php mysqli registration

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

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

$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();
}

2 个答案:

答案 0 :(得分:1)

你混合了Procedural style&amp; Object 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

答案 1 :(得分:0)

$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!";
}