INSERT INTO SQL php函数不起作用

时间:2016-02-10 01:02:33

标签: php mysql mysqli prepared-statement

我设法编写了一个php脚本,用于检查数据库中是否已存在用户名,并且只有新用户尚不存在才会添加。

这是我的php脚本:

<?php
require "init.php";

if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $forename = $_POST['forename'];
    $username = $_POST['surname'];
    $password = $_POST['password'];

    $stmt = "SELECT username FROM users WHERE username = ?";
    $result = $dbcon -> prepare($stmt);
    $result->bind_param('s', $username);
    $result->execute();
    $result->bind_result($username);

    if($result->fetch()){
        echo "Can't add new user as it already exists!";
    }
    else{
        $stmt_two = "INSERT INTO users (username, forename, surname, password) 
                VALUES(?, ?, ?, ?)";
        $result_two = $dbcon -> prepare($stmt_two);
        $result_two->bind_param('ssss', $username, $forename, $surname, $password);
        $result_two->execute();
        $result_two->close();
        echo json_encode("Success");
    }
}
?>

我认为由于我有多个准备好的声明,因此不会间歇性地插入或插入记录。如果我只使用INSERT INTO语句单独执行SELECT FROM语句,则会立即添加记录。

为什么这和我的代码有什么问题?

由于

1 个答案:

答案 0 :(得分:4)

正如我在评论中所说,不要过于复杂,只需检查找到的行数。无需取任何东西。您只是检查该用户是否存在。

$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();

if($result->num_rows() > 0) { // if it exists

} else {
    // make your insertions
}

另一个说明:

isset可以带有多个参数:

if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
    // and so on
}

编辑:另一种风格(使用MySQL的COUNT()):

$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();

if($count > 0) { // exists

} else {
    // do something else
}