[英]If/else error message to PHP MYSQL query
我有一個簡單的查詢(AJAX)。 我注意到,如果$insert_stmt
不執行,我仍然會收到一條成功消息。
if ($insert_stmt = $mysqli->prepare("INSERT INTO `alerte` (`nom_alerte`, `country`, `date_debut_alerte`) VALUES (?, ?, ?)")) {
$insert_stmt->bind_param('sss', $alert_name, $country, $start_alert_date);
$insert_stmt->execute();
$reponse = 'success';
} else {
$reponse = 'Sorry, a database error occurred; please try later';
}
echo json_encode(["reponse" => $reponse]);
我想知道是否可以添加另一個if / else語句來驗證執行
我嘗試過類似的方法,但是我不確定它的編碼是否正確:
if ($insert_stmt = $mysqli->prepare("INSERT INTO `alerte` (`nom_alerte`, `country`, `date_debut_alerte`) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('sss', $alert_name, $country, $start_alert_date);
// inserted part if/else check
if (! $insert_stmt->execute()) {
$reponse = 'Sorry, a database error occurred; please try later';
} else {
$reponse = 'success';
}
} else {
$reponse = 'Sorry, a database error occurred; please try later';
}
有人可以告訴我是否合適或是否有更好的方法?
請像這樣逐步調試代碼。
如果有的話,它一定會給您帶來錯誤。
if ($stmt = $mysqli->prepare("INSERT INTO `alerte` (`nom_alerte`, `country`, `date_debut_alerte`) VALUES (?, ?, ?, ?)")) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param('sss', $alert_name, $country, $start_alert_date)){
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}else {
$reponse = 'success';
}
一旦犯錯。 您可以稍后相應地更改代碼。
希望這可以幫助您輕松找到錯誤!
我不確定來自alerte
的列的類型,但是我認為錯誤是每個插入值處被遺忘的引號...
嘗試這個:
INSERT INTO `alerte` (`nom_alerte`, `country`, `date_debut_alerte`) VALUES ('?', '?', '?')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.