我有一個POST PHP腳本,我想檢查POST數據是否已經存在於數據庫中,如果它確實存在,則拋出錯誤消息,如果它不將它添加到數據庫並且成功信息。Mysqli_num_rows無法正常工作
它成功地增加了,但如果我嘗試添加已經存在的名稱,它提供了錯誤:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, string given in
和反正添加新的數據。
代碼:
<?php // _POST Add Major Category
if(isset($_POST['AddMajorCat']))
{
// Declare _POST Variables
$POSTNewMajorCatName = $_POST['MajorCatName'];
// Check if name exists in database
include_once('connection.php'); // db connection
$query = "SELECT *
FROM DowntimeCategoriesMain
WHERE DowntimeCategoriesMain.maincategory = '$POSTNewMajorCatName'";
$response = mysqli_query($db, $query); // Send Statement
$NumRows = mysqli_num_rows($query); // Count number of rows
if ($NumRows != 0) {
$messageSendTitle = "Uh-oh!";
$messageSend = "Major Downtime Category " . $POSTNewMajorCatName ." already exists. Unable to add Category.";
$messageSendType = "error";
}
else { // If name doesn't exist in database, add
include_once('connection.php'); // db connection
$query = "INSERT INTO DowntimeCategoriesMain (maincategory)
VALUES ('$POSTNewMajorCatName')";
$response = mysqli_query($db, $query); // Send Statement
if ($response) { // Successful
$messageSendTitle = "Success!";
$messageSend = "Major Category " . $POSTMajorCatName . " was added. ";
$messageSendType = "success";
}
else { // Unsuccessful
$messageSendTitle = "Uh-oh!";
$messageSend = "There seems to be a problem. MySQL Error: " . mysqli_error($db);
$messageSendType = "error";
}
} // else statement
} // If _POST is set statement
?>
我試圖交換mysqli_num_rows($query);
爲$query->num_rows;
,它不再顯示錯誤,但還是增加了數據。
請使用準備好的語句。 –
'$ NumRows = mysqli_num_rows($ response);' – Jeff