林做一個函數來改變從表中的用戶密碼,但即時得到一個語法錯誤更新表使用PDO:語法錯誤
下面是函數:
public function changepassword($password, $newpassword) {
$user_id = $_SESSION["userSession"];
$stmt = $this->db->prepare("SELECT * FROM user WHERE user_id=:user_id");
$stmt->execute(array(":user_id" => $user_id));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($password = $userRow['password']) {
$sql = "UPDATE user set password=:password WHERE user_id=:user_id";
$stmt2 = $this->db->query($sql);
$stmt->execute(array(":user_id" => $user_id, ":password" => $password));
$stmt2->execute();
return true;
} else {
return false;
}
}
這是函數調用
if (isset($_POST['btn-save'])) {
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$newpassword2 = $_POST['newpassword2'];
if ($newpassword == $newpassword2) {
if ($user->changepassword($password, $newpassword)) {
header("Location: selfedit.php?inserted");
} else {
header("Location: selfedit.php?failure");
}
} else {
header("Location: selfedit.php?failurematch");
}
}
這是錯誤我得到:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':password WHERE user_id=:user_id' at line 1' in C:\xampp\htdocs\aDatabase2\class.user.php:37 Stack trace: #0 C:\xampp\htdocs\aDatabase2\class.user.php(37): PDO->query('UPDATE user set...') #1 C:\xampp\htdocs\aDatabase2\selfedit.php(8): USER->changepassword('fereira', 'umdois') #2 {main} thrown in C:\xampp\htdocs\aDatabase2\class.user.php on line 37
編輯1
我根據這個問題的意見改變了功能,讓不同的錯誤
public function changepassword($password, $newpassword) {
$user_id = $_SESSION["userSession"];
$stmt = $this->db->prepare("SELECT * FROM user WHERE user_id=:user_id");
$stmt->execute(array(":user_id" => $user_id));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($password == $userRow['password']) {
$sql = "UPDATE user set password=:newpassword WHERE user_id=:user_id";
$stmt2 = $this->db->prepare($sql);
$stmt2->execute(array(":user_id" => $user_id, ":password" => $newpassword));
return true;
} else {
return false;
}
}
新的錯誤:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in C:\xampp\htdocs\aDatabase2\class.user.php:37 Stack trace: #0 C:\xampp\htdocs\aDatabase2\class.user.php(37): PDOStatement->execute(Array) #1 C:\xampp\htdocs\aDatabase2\selfedit.php(8): USER->changepassword('ferreira', 'anotherpass') #2 {main} thrown in C:\xampp\htdocs\aDatabase2\class.user.php on line 37
我不使用PDO,但是這可能'準備()','不查詢()'。 – Blackhole
@黑洞是正確的。 'query()'用於簡單查詢,但'prepare()/ execute()'必須與參數一起使用。 –
在if - $ stmt中綁定了2個'execute()',而$ stmt2沒有。這將是你錯誤的原因。 – Tristan