无法使用PHP中的准备好的语句将数据插入数据库,未报告错误

时间:2018-12-02 01:01:19

标签: php mysqli prepared-statement

我正在尝试创建一个注册表单,将用户输入的数据存储到MySQL数据库中。 我可以通过手动设置值来使其工作,但了解到最好使用准备好的语句。这就是我的PHP代码:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "accounts";

//Creating a new connection to the database
$connection = new mysqli($servername, $username, $password, $dbname);

//Checking the connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

//SQL string used to insert the data into the database
$sql = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";

$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "Failed";
} else {
    mysqli_stmt_bind_param($stmt, "sss", $_POST["name"], $_POST["email"], $_POST["passowrd"]);
    mysqli_stmt_execute($stmt);
}
?>

这是HTML:

<div id="wrapper">
    <div id="formContent">
        <h3>Complete the following form to register an account:</h3>

        <form class="register" action="registration.php" method="post">

            Email: <input type="email" name="email" required> <br></br>
            Name: <input type="name" name="name" required> <br></br>
            Password: <input type="password" name="password" required> <br></br>
            Confirm Password: <input type="password" name="confirmed_password" required> <br></br>
            <input type="submit" name="submit">

        </form>
    </div>
</div>

列出的代码未返回任何错误,但数据库未更新。我已经抽空了一段时间,所以能提供任何帮助。

1 个答案:

答案 0 :(得分:2)

首先,您有password的错字(您有$_POST['passowrd']),第二,这是基于文档中的示例:

# Prepare (use the OOP version of this library)
$query  =   $connection->prepare("INSERT INTO users (`name`, `email`, `password`) VALUES (?, ?, ?)");
# Bind parameters and spell "password" correctly
$query->bind_param('sss', $_POST['name'], $_POST['email'], $_POST['password']);
# Execute
$query->execute();
# See if the row was created and echo success
echo ($query->affected_rows > 0)? 'Success!' : 'Failed';

您应该使用password_hash()(存储)和password_verify()(验证)或等效的bcrypt库(如果您的php版本没有这些本机函数)。使用这些功能时,请确保您的password列的长度为255个字符,以免切断密码哈希。