此问题已经在这里有了答案:
我有一些PDO代码,即使该行未成功插入数据库,也不会出现错误...
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO reservations (bookingdatetime, remoteip)
VALUES (:bookingdatetime, :remoteip)");
$stmt->bindParam(':bookingdatetime', $bookingdatetime);
$stmt->bindParam(':remoteip', $remoteip);
// insert a row
$stmt->execute();
$bookingid = $conn->lastInsertId();
echo json_encode(array("title" => "WE DID IT!", "body" => " The row # " . $bookingid . " was made!"))
} catch(PDOException $e) {
echo json_encode(array("title" => "Database Error", "body" => $e->getMessage()));
}
$conn = null;
编辑:我应该说,即使没有成功创建该行,它仍然给出一个“我们做到了!”消息,并且行ID返回为0
编辑2:如果我在我的prepare语句列名称上输入类型,它仍将返回“ WE DID IT” ...这将是一个明显的错误。
有一个函数rowCount
,它说明上一个查询插入/更新的行数
$stmt->execute();
$rowCount = $stmt->rowCount();
$bookingid = $conn->lastInsertId();
if($rowCount > 0)
echo json_encode(array("title" => "WE DID IT!", "body" => " The row # " . $bookingid . " was made!"));
else
echo json_encode(array("title" => "Database Error", "body" =>"Insert Failed"));