我有一个POST PHP脚本,我想检查POST数据是否已经存在于数据库中,如果确实存在,抛出错误消息,如果它没有将它添加到数据库并给出成功消息。
它成功添加,但如果我尝试添加已存在的名称,则会出错:
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;
,但不再显示错误,但仍会添加数据。
答案 0 :(得分:2)
您是否真的阅读过错误消息?它告诉你到底出了什么问题。 $query
是一个字符串,它需要mysqli_result
,在您的情况下为$response
:
$response = mysqli_query($db, $query);
$NumRows = mysqli_num_rows($response);
答案 1 :(得分:2)
错误消息会提示您问题是什么。 mysqli_num_rows
期望将资源作为参数。你给它的是$query
变量,它是一个字符串。您要提供给mysqli_num_rows
的资源位于$response
变量中。所以你想要的是这样的:$NumRows = mysqli_num_rows($response);
此外,通过将$POSTNewMajorCatName
变量直接连接到您的查询字符串中,您可以自己开启SQL注入攻击。您可以使用预准备语句来防止这种情况。您将使用mysqli_prepare
函数。您可以在此处查看文档mysqli_prepare
答案 2 :(得分:0)
您已将$query
作为mysqli_num_rows()
的参数传递,而$response
依次是基于您的代码的字符串。您必须通过$NumRows = mysqli_num_rows($response);
:
t = df.groupby(lambda r: df.ix[r,'A']).aggregate(np.sum)
t.index.name = 'foobar'
t
Out[7]:
B C
foobar
W 1 1
X 5 5
Z 2 3