我想讓我的網站免受sql注入。所以我決定改變我的代碼並用準備好的語句替換它。我認爲我在下面的代碼中犯了一個小錯誤。在連接數據庫期間準備的語句
<?php
session_start();
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn= mysqli_connect($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
if ($password!==$rpassword) {
$_SESSION['err']="Passwords did not match, please try again!";
header("Location: index.php");
$conn->close();
}
else {
$stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
if(!$stmt){
echo "false";
}else {
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
if ($stmt->execute === TRUE) {
$redirectUrl = 'index.php';
$_SESSION['registrationsuccessful']="Your account was successfully created! You may now log in to your account.";
header("Location: index.php");
}else{
$_SESSION['alreadyexists']="Username or email already exists!";
header("Location: index.php");
$stmt->close();
$conn->close();
}
$stmt->close();
$conn->close();
}
}
我現在面臨的問題是,我得到消息「用戶已存在」當我試圖創建一個實際上並不存在的賬號。謝謝!
不要調用'$ stmt-> execute()'兩次 - 而是將它分配給一個變量並測試它是否爲真 – RamRaider