问题描述
我有一个POST php脚本,我想检查数据库中是否已经存在POST数据,如果存在,则抛出错误消息,如果没有将其添加到数据库中并给出成功消息.
I have a POST php script that I'm wanting to check if the POST data already exists in the database and if it does, throw error message, if it doesn't add it to database and give success message.
它添加成功,但是如果我尝试添加一个已经存在的名称,则会出现错误:
It adds successfully but if I try and add a name that already exists, it gives error:
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;
,它不再显示错误,但仍添加了数据.
I have tried exchanging mysqli_num_rows($query);
for $query->num_rows;
and it no longer shows error, but still adds the data.
推荐答案
您真的读过错误消息吗?它确切地告诉您哪里出了问题. $query
是一个字符串,它需要一个mysqli_result
,在您的情况下为$response
:
Did you actually read the error message? It tells you exactly what is wrong. $query
is a string, and it wants a mysqli_result
, which is $response
in your case:
$response = mysqli_query($db, $query);
$NumRows = mysqli_num_rows($response);
这篇关于Mysqli_num_rows无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!