-1

I have this code below and it works fine except when I refresh the page it inserts a blank row. Does anyone know what I need to do here?

<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);

$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded'; 

mysqli_close($con);
?>

I tried finding conditional if statements that can keep the code from creating blank rows but to no avail have I found a working solution.

Any help is appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
WebEducate
  • 79
  • 2
  • 17

1 Answers1

-1
<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (empty($_POST['inv_number']) || empty($_POST['date']) ||empty($_POST['date_type'])
    || empty($_POST['item1']) || empty($_POST['location1'])) 
    {
      echo "Re direct user by using header or show them messages";

    }
else {
    // set your variable and run your query 
    //i just copy and posted your code from your question
// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);

$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded'; 
}
mysqli_close($con);
?>

Important to note your query will not run, if any of the feild which is given in if statement are empty

Please read the comment in the solution

arif_suhail_123
  • 2,509
  • 2
  • 12
  • 16