Search code examples
phpmysqliisset

How to stop empty submits from posting to database?


I'm new to PHP. I added in the isset command, and the form is working with the database but every time I bring up this page it automatically submits a blank record to my database. How can I make it so that it only runs through the PHP commands if an input is entered and a user hits submit?

<?php
$handle = isset($_POST['handle']);
$address = isset($_POST['address']);
$code = isset($_POST['code']);

$rrr=mysqli_connect("localhost","knock_knock","whosthere","1");
if (mysqli_connect_errno()) {
echo "Connection to DB failed" . mysqli_connect_error();
}

$handle2 = mysqli_real_escape_string($rrr, $handle);
$address2 = mysqli_real_escape_string($rrr, $address);
$code2 = mysqli_real_escape_string($rrr, $code);

if(empty($handle)){
echo "Handle can not be empty";
}

$sql="INSERT INTO players (Handle, Address, Code)
VALUES ('$handle2', '$address2', '$code2')";

 if (!mysqli_query($rrr,$sql)) {
die ('Error: ' . mysqli_error($rrr));
}
echo "Record added";

mysqli_close($rrr);
?>

Solution

  • $handle = isset($_POST['handle']);
    $address = isset($_POST['address']);
    $code = isset($_POST['code']);
    

    the above code will store true in all the variables if the are set.it should be -

    $handle = isset($_POST['handle']) ? $_POST['handle'] : false;
    $address = isset($_POST['address']) ? $_POST['address'] : false;
    $code = isset($_POST['code']) ? $_POST['code'] : false;
    

    and all code that is supposed to be executed after the form submit should be placed in -

    if (isset($_POST['submit'])) {
        //code to be executed
    } 
    

    submit or whatever the field is for submit button. and then the checks should be added for empty values.

    you have to stop the execution or redirect.

    if(empty($handle)){
        header('location:page.php?msg=yourmessage');
        exit;
    }
    

    or

    if(empty($handle)){
        echo "Handle can not be empty";
        exit;
    }