user3741085 user3741085 - 3 months ago 9
MySQL Question

Blank row inserted before new data row in Mysql database

a blank row is being inserted before and along with the actual data row in my Mysql Database.Why is this?

Here is my code:

<?php

define('DB_NAME','my_db_name');
define('DB_USER','my_db_user');
define('DB_PASSWORD','my_db_pass');
define('DB_HOST','localhost');

$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

if (!$link){
die('Could no connect'.mysql_error());

}

$db_selected = mysql_select_db(DB_NAME, $link);

if(!$db_selected){
die('Can\'t no connect'. DB_NAME .':'.mysql_error());

}

$name = $_POST['name'];

$sql ="INSERT INTO demo (name) VALUES ('$name')";

if(!mysql_query($sql)){

die('Error:'.mysql_error());
}

mysql_close();

?>
<html>
<body>
<form action="demo2.php" method="post">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md" required="">
<input type="submit" class="btn btn-success" value="Add Client">
</form>
</body>
</html>


Here is my Mysql database Structure:

Mysql database Structure

Here is the table with a blank entry before the "gunk" name data entry:

enter image description here

I have taken the time to isolate this issue down to one form input with a successful database connection and my data is added, just with blank row before it.

Why am I getting a blank row inserted before new data row in my database?

Answer

You're using the same script to display the form and to process the form submission. But when it inserts into the DB, it's not checking whether it's being run in response to the user opening the form for the first time or submitting it. When they go to the URL the first time, $_POST is empty, so you insert a blank value. Add a check for this.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

    if (!$link){
     die('Could no connect'.mysql_error());

    }

    $db_selected = mysql_select_db(DB_NAME, $link);

    if(!$db_selected){
     die('Can\'t no connect'. DB_NAME .':'.mysql_error());

    }

    $name = $_POST['name'];

    $sql ="INSERT INTO demo (name) VALUES ('$name')";

    if(!mysql_query($sql)){

      die('Error:'.mysql_error());
    }

    mysql_close();

}