SgtDrPeppers SgtDrPeppers - 7 months ago 21
SQL Question

Why is my MySQL database adding empty rows?

I'm learning PHP and SQL by running MAMP on my Mac, and accessing the database through phpMyAdmin.

I've made one PHP script to add a new user to a table, one for comparing inputted data with the table (login) and one to close an account. All of the scripts are very basic and the data isn't sanitized at all, as I'm just getting used to the basics of PHP.

I've noticed that after I run the script for account creation (inserting data), a few seconds after the script is run, a new row is added to the table with an id (which I've set to auto increment) but no other data.

I'm just wondering if the reason for this is something obvious in MySQL that I'm just missing.

The following is the account creation script:

<?php
//Get values from HTML form
$varUsername = $_POST['username'];
$varPassword = $_POST['password'];
$varPasswordHash = password_hash($varPassword, PASSWORD_DEFAULT);

//Establish connection to database
$server = "localhost";
$username = "root";
$password = "root";
$database = "members";

$connection = mysqli_connect($server, $username, $password, $database);
if(!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}

//Send data to database
$action = "INSERT INTO details (USERNAME, PASSWORD) VALUES ('$varUsername', '$varPassword')";

if(mysqli_query($connection, $action))
{
echo 'Account created.';
}
else
{
echo 'Account creation failed: ' . mysqli_error($connection);
}

mysqli_close($connection); //End connection to database
?>


and the HTML form to go with it:

<html>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>

Answer

I'm making a guess right now...

I would add an extra if-statement to the script itself. Like this:

if (isset($_POST['submit-form'])) {
    // All the above to insert the data into the script...
}

It would make sense if you visit the sign_up.php itself and notice there is a new entry made into your database.

You'll have to modify your HTML a little, to make the if-statement work.

Just add name='submit-form' to the submit button: <input type="submit" name="submit-form">

This will make the script more complete.

Also a little update on the matter as I just read that it adds an empty row after you submit an empty form.

You can check wether the fields are filled in with, guess what, another if-statement:

if (empty($_POST['username'])) {
    echo 'Please enter your username...';
} else
if (...)