简体   繁体   中英

PHP sending blank information to the database

I am using a Unity form in conjunction with PHP to send data to a database, I can successfully enter information in and it reaches the database but the problem is it also sends the data if the fields are empty.

I am trying to prevent this using the isset method but it doesn't appear to be working. Can somebody double check this for me?

Image of data reaching the database

在此处输入图片说明

Image of unity form

在此处输入图片说明

<?php

    if(!isset($_POST['usernamePost'], $_POST['passwordPost'], $_POST['emailPost']))
    {
        echo "This is not working";
    }
    else
    {
    //Enter the data into the database
    $username = filter_var($_POST['usernamePost'], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST['passwordPost'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['emailPost'], FILTER_SANITIZE_STRING);

    //variable for connection
    $servername = "localhost";
    $server_username = "root";
    $server_password = "";
    $dbName = "ontrigger_game";

        try
        {
            //connection to the database
            $dbhandle = mysqli_connect($servername, $server_username, $server_password) 
              or die("Unable to connect to MySQL");
            echo "Connected to MySQL<br>";

            //select a database to work with
            $selected = mysqli_select_db($dbhandle, $dbName)
                    or die("Could not select database");

            $sql = "INSERT INTO users (username, password, email)
                VALUES ('".$username."','".$password."','".$email."')";
            if(!mysqli_query($dbhandle, $sql))
            {
              die('Error: ' . mysqli_error());
            }
            echo "1 record added";

            //close the connection
            mysqli_close($dbhandle);

        } 
        catch (Exception $ex) 
        {

        }
    }
?>

You should also check if its empty by using the empty() method

if (!isset($_POST['usernamePost']) && empty($_POST['usernamePost'] )) {

// error message here

} else {

// What you want to do if not empty and is set.

}

Note: Use the && operator instead of comma's

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