我读过几篇关于这个问题的文章,但没有一篇对我有帮助,我有点困惑该怎么办。
基本上,我想检查sql查询是否执行得没有任何错误。要做到这一点,我是否必须同时使用下面显示的两个if
语句?
if($stmt = $mysqli->prepare("INSERT INTO table VALUES (?, ?, ?);"))
{
$stmt->bind_param("sss", $a, $b, $c);
if(!$stmt->execute())
{
// Do I have to catch the problem here?
}
if($stmt->affected_rows === -1){
// Do I have to catch the problem here?
}
$stmt->close();
}
else
{
// Do I need to catch the problem here?
}
您应该检查prepare()
、bind_param()
和execute()
的返回值。如果失败,它们都返回false
。
如果execute()
没有返回false
,那么INSERT
应该已经成功通过,因此只有当您想知道有多少行受到影响时,检查affected_rows
才有意义。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
把这行放在mysqli连接的上面。这就是你所需要的。
若要将问题通知用户,请检查AJAX请求的响应状态。如果是500,那么保存就有问题了。