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
and adds the new data anyways.
Code:
<?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
?>
I have tried exchanging mysqli_num_rows($query);
for $query->num_rows;
and it no longer shows error, but still adds the data.