简体   繁体   中英

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>

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM