0

I am trying to make a VERY simple PHP form that posts a form to MySQL Database, however I am having some issues, and would welcome a simple fix for this if possible:

My PHP:

<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO Persons (email, type, cats)
VALUES
('$_POST[email]','$_POST[type]','$_POST[cats]')";

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

mysqli_close($con);
?>

My HTML:

<form action="personuploader.php" method="post">

        <table class="#"> 

            <tr>

                <th colspan="2">Test</th>

            </tr>

            <tr>

                <td>Email Address:</td>

                <td><input type="text" name="email"> </td>

            </tr>

            <tr>

                <td>Type:</td>

                <td><input type="text" name="type"> </td>

            </tr>

            <tr>

                <td>Cats:</td>

                <td><input type="text" name="cats"> </td>

            </tr>

            <tr>

                <td></td>

                <td><input type="submit" value="upload" name="upload">

            </tr>

        </table>  

    </form>

My SQL Configuration:

SQL

Even though I have not null set in the DB I am getting empty results, is it possible to stop the form resubmitting on refresh causing null results be entered into the DB. I will enter some form validation to stop null results passing into the post script in the future but refreshing the page still sends over null results.

3
  • 1
    To avoid re-submissions causing a NULL entry, you can always use a header to redirect to another page, or use AJAX. However, am sure there are other ways of doing this in the query itself, I just don't remember how right now. I.e.: In place of where you have echo "1 record added"; you can do header("Location: added.php"); exit(); --- You can also use a conditional statement if(empty($_POST['variable'])){ die("Fill this in.");} Commented Jan 6, 2014 at 22:00
  • 3
    Food for thought: Don't use this method VALUES ('$_POST[email]','$_POST[type]','$_POST[cats]') you're open to SQL injection Commented Jan 6, 2014 at 22:04
  • On a relational database (unless it's Oracle) an empty string is NOT THE SAME THING as NULL Commented Jan 6, 2014 at 22:31

3 Answers 3

1

Edit:

Your column names have mixed-case letters (Cats and cats are not the same)

I edited my answer, where I changed it from:

$sql="INSERT INTO `Persons` (`email`, `type`, `cats`)

to

$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`)

I also made a mistake with a missing ) for if(empty($_POST['email'] which has been fixed.

Please make sure also, that your column names are indeed called Email Type Cats and not email type cats Change it to the letter-case that is in your DB.

Your table's original structure: (larger image) enter image description here


See the rest below in the code.


As I stated in my comments under your original question, have put this together for you.

  • Don't use this method VALUES ('$_POST[email]','$_POST[type]','$_POST[cats]') you're open to SQL injection

  • To avoid re-submissions causing an empty entry, you can use a header() to redirect to another page, or use AJAX

However, I am sure there are other ways of doing this in the query itself, I just don't remember how right now.

I.e.: In place of where you have echo "1 record added";

you can do header("Location: added.php"); exit();

You can also use a conditional statement:

if(empty($_POST['variable'])){ die("Fill this in.");}

Try the following. It will check for empty fields, as well as check if the upload submit-type button is set.

Plus, I modified the way your query was done, replacing POST variables with mysqli_real_escape_string()

<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if(isset($_POST['upload'])){

// You can replace the || with && if required
// depending on what you want to check for.
    if(empty($_POST['email']) || empty($_POST['type']) || empty($_POST['cats']))
    {
    die("You need to fill in all the fields.");
    }

$email = mysqli_real_escape_string($con, $_POST['email']);
$type = mysqli_real_escape_string($con, $_POST['type']);
$cats = mysqli_real_escape_string($con, $_POST['cats']);

$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`) 
VALUES ('$email','$type','$cats')";

    if (!mysqli_query($con,$sql))
    {
    die('Error: ' . mysqli_error($con));
    }
    
// Uncomment out if you're going to use echo, but not with header.
// echo "1 record added";

header("Location: redirect_to_other_page.php");
exit();

} // end of if(isset($_POST['upload']

// else conditional statement for if(isset($_POST['upload']
else{ echo "You cannot do this operation from here."; }

mysqli_close($con);
?>

Footnotes:

Just saying, the following:

('$_POST[email]','$_POST[type]','$_POST[cats]')

should have been:

('$_POST['email']','$_POST['type']','$_POST['cats']')

However, using this method is highly discouraged, as I already mentioned.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for this, when I post from my form to this page "personuploader.php" using your PHP script and I am getting no results passed through to the Personuploader using my form as above, no errors and this doesntt work: header("Location: redirect_to_other_page.php"); exit();
I like your solution, but Any idea's to get it work?
I think I know what's wrong. Your column names have upper case letters (Cats and cats are not the same) I edited my answer, where I changed it from $sql="INSERT INTO Persons` (email, type, cats)` to $sql="INSERT INTO Persons` (Email, Type, Cats)` @Dan
And the header("Location: redirect_to_other_page.php") you need to create a page called redirect_to_other_page.php and put a thank you message of sorts. @Dan it will work once the DB is successfully updated.
0

You need to check if a submit actually occured:

if ($_SERVER["REQUEST_METHOD"] == 'POST') {
    ... submit occured, do DB stuff
}

And note that an empty string is NOT the same as an SQL null. Empty string is just that - a string which happens to be empty/zero-length. An SQL null is quite literally "unknown". Your code cannot insert an actual null - it can only ever insert empty strings.

Comments

0

You should check whether the Upload button has been clicked on the "personuploader.php" file.

// Initializing Variables
$email = '';
$type  = '';
$error = false;    

if ( isset ( $_POST['upload'] ) ) {

    // Then capture the POST Variables
    $email = $_POST['email'];

    // Do Some Validations
    if ($email == '') {
        $error = true;
    }

    // Process the Form if NO Errors

    if ($error == false) {

        // Insert The Data into DB
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.