[英]Failing to insert data into database using prepared statement in PHP, no error reported
我正在嘗試創建一個注冊表單,用於將用戶輸入的數據存儲到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>
列出的代碼未返回任何錯誤,但數據庫未更新。 我已經抽空了一段時間,所以對您的幫助表示感謝。
首先,您輸入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個字符,以免切斷密碼哈希。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.