Achy Achy - 5 months ago 8
HTML Question

Trouble with checking empty value

So, i have some trouble with checking empty value. How can i fix this problem? I want to check if category_name exist in database (its working), and i want to check if input is empty (thats not work). Here is my code:

PHP:

<?php
error_reporting(E_ERROR);
include("../db_config.php");
$category = mysqli_real_escape_string($conn, $_POST['category']);
$result = "SELECT * FROM category WHERE category_name='$category'";
$rs = mysqli_query($conn,$result);
$data = mysqli_fetch_array($rs);
if($data > 1 || $category === NULL)
{
echo "<script>
alert('Category name already exist or the value is empty.');
window.location.href='category.php';
</script>";
}

else
{
$sql[0] = "INSERT INTO category (category_name) VALUES ('$category')";
if(mysqli_query($conn, $sql[0]))
{
header("Location:category.php");
exit();
}
else
{
echo "ERROR: Could not able to execute $sql[0]. " . mysqli_error($conn);
}
$conn->close();
}
?>


HTML:

<form action="category_insert.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="mode" value="add">
Name:<br />
<input type="text" name="category" placeholder="Category name"><br><br>
<input type="submit" value="Submit"><br><br>
</form>

Answer

Function mysqli_real_escape_string return escaped string (as you can read in documentation here http://php.net/manual/en/mysqli.real-escape-string.php) so there is no possible to expect NULL in $category variable. Replace this part of your code

if($data > 1 || $category === NULL)

with this

if($data > 1 || empty($category))