这是编写PDO更新语句的正确方法吗?我基于我在网上看到的教程,但它在AJAX解雇时似乎没有做任何事情(即使AJAX请求在控制台中被记录为成功,也没有对数据库进行更新): / p>
$duedate = $_POST["duedate"];
$status = $_POST["status"];
$id = $_POST["id"];
$sql = "UPDATE pm_schedule SET duedate=?, status=? WHERE id=?";
$q = $pdo->prepare($sql);
$q->execute(array($duedate,$status,$id));
答案 0 :(得分:5)
是的,这是正确的,但你需要告诉PDO在错误时引发错误 所以,建立你的连接代码:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
确保您可以看到PHP错误。所以,你知道出了什么问题。
答案 1 :(得分:2)
$duedate = $_POST["duedate"];
$status = $_POST["status"];
$id = $_POST["id"];
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $pdo->prepare('UPDATE `pm_schedule` SET `duedate` = ?, `status` = ? WHERE `id` = ?');
$sql->execute(array($duedate, $status, $id));
} catch(PDOException $e) {
echo $e->getMessage();
}
PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION
这有助于您找到错误
使用try
和catch
,您可以收到echo
错误消息,告知其失败的位置和原因。
答案 2 :(得分:0)
理解PDO非常好tutorial
正确的方法是:
// Named Placeholders
$sSql = "UPDATE mytable SET FName = :FName, LName = :LName, Age = :Age, Gender = :Gender WHERE ID = :ID;";
// PDO prepared statement
$oSth = $oDbh->prepare($sSql);
// Bind Named Placeholders
$oSth->bindParam(":FName", $FName, PDO::PARAM_STR);
$oSth->bindParam(":LName", $LName, PDO::PARAM_STR);
$oSth->bindParam(":Age", $Age, PDO::PARAM_INT);
$oSth->bindParam(":Gender", $Gender, PDO::PARAM_STR);
$oSth->bindParam(":ID", $ID, PDO::PARAM_INT);
// Execute PDO with condition
if ($oSth->execute()) {
// Get Affected row
$iAffectedRows = $oSth->rowCount();
$oSth->closeCursor();
return $iAffectedRows;
} else {
// PDO error, could also be caught in a try/catch statement
$errorMsg = $oSth->errorInfo();
error_log(json_encode($errorMsg));
}