Multiple records added in phpMyAdmin when submitting form

I created a form using html and php. When I press the submit button, 3 identical records are added into phpMyAdmin instead of just one.

I started having this issue when I implemented some CSS.

Thank you to those who can help with this issue.

<?php

session_start ();

if(!isset($_SESSION['username'])){
    header('location:login.php');
}

 ?>

<!doctype html>
	<html>
	<head>
		<title>Consumables Log</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link rel="stylesheet" type="text/css" href="includes/style.css">
	</head>
   <body>
       <div class="login-box">
       <img src="images/logo.png" class="logo">

         <h1>Consumables Log</h1>

         <form action="insertconsumables.php" method="POST">
			
	     <p><label> Date </label>
	     <input type="date" name="date" placeholder="Date" required></p>
                               			
	     <p><label> Truck Number </label>
	     <input type="integer" name="truckno" placeholder="Truck Number" required><p>
                         
	     <label> Diesel Amount </label>
	     <input type="decimal" name="diesel" placeholder="Diesel (gal)">

	     <label> DEF Amount </label>
	     <input type="decimal" name="def" placeholder="DEF (gal)">

	     <label> Absorbent Amount </label>
	     <input type="decimal" name="absorbent" placeholder="Fraction Of Bag">

	     <button type="submit"> Submit </button>

	</form>

<br></br>

      <form action="logout.php" method="post">
       <input type="submit" name="logout" value="Log Out">      
      </form> 

</div>
	</body>
	</html> 

Welcome to the forums rommelhernandez89

You will have to show us some code if anyone is going to help you.

1 Like

Hereā€™s the code. Iā€™m fairly new at this.

 <!DOCTYPE html>
 <html lang="en" dir="ltr">
   <head>
     <meta charset="utf-8">
     <title>Submit Page</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link rel="stylesheet" type="text/css" href="includes/style.css">

   </head>
   <body>
       <div class="login-box">
       <img src="images/logo.png" class="logo">

<?php
$date= $_POST['date'];
$truckno = $_POST['truckno'];
$diesel= $_POST['diesel'];
$def = $_POST['def'];
$absorbent = $_POST['absorbent'];
$uname= $_SESSION ['username'];

$insert="INSERT INTO consumables (id, date, truckno, diesel, def, absorbent, username) VALUES (NULL, '$date', '$truckno', '$diesel', '$def', '$absorbent','$uname');";

mysqli_query ($con,$insert);

$result = mysqli_query ($con,$insert);

if (mysqli_query($con, $insert)) {
    echo "Thank you! Your entry was submitted successfully.";
} else {
    echo "Error: " . $insert . "<br>" . mysqli_error($con);
}
?>

   <h2>What would you like to do next, <?php echo $_SESSION ['username']; ?>?</h2>

<div align="left">
   <a href="consumables.php"><font size="4" color="white"><u>Add More Consumables</u></font></a>
</div>
 <br>
      <form action="logout.php" method="post">
       <input type="submit" name="submit" value="Log Out">      
      </form> 
   </body>
 </html>

remove this line

mysqli_query ($con,$insert);

$result = mysqli_query ($con,$insert)
2 Likes

Thank you! That works. :raised_hands:

One more issue Iā€™m having is when the user clicks the back button and hits the submit button again a new record is added containing the old information. Is there a way to clear the form so that the user will have to enter new values again even when the user uses the back button?

you need to add hidden field

<input type='hidden' name='post_id' value='<?php createPassword(64);?>'>

Then in your code do this:

if( ($_SESSION['post_id'] != $_POST['post_id']) )
{
    $date= $_POST['date'];
$truckno = $_POST['truckno'];
$diesel= $_POST['diesel'];
$def = $_POST['def'];
$absorbent = $_POST['absorbent'];
$uname= $_SESSION ['username'];

$insert="INSERT INTO consumables (id, date, truckno, diesel, def, absorbent, username) VALUES (NULL, '$date', '$truckno', '$diesel', '$def', '$absorbent','$uname');";


$result = mysqli_query ($con,$insert);

if ($result) {
    echo "Thank you! Your entry was submitted successfully.";
} else {
    echo "Error: " . $insert . "<br>" . mysqli_error($con);
}
} else {
    //normal display
}

function createPassword($length)
{
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= ($length - 1)) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}

Give a try.

Will this force the user to log in again? I donā€™t want to force the user to log in again?

no, this will not

As @Azer_Qurbanov pointed out, you execute the query three times, therefore get three inserts.
You only need the one in the if condition.

You should have a test in there to check for a form submision and only run the form parsing code then.

if($_SERVER['REQUEST_METHOD'] == 'POST'){
   // Parse form
}

Thatā€™s OK, but I will point out some beginner mistakes you have to improve your coding.
First your HTML.

Using the lang attribute is good, but you can be even more specific with English saying whether itā€™s en-gb (Great Britain) en-us (United States) or any other version of the language.
There is no need for the dir attribute as ltr is default.

The align attribute and font element are obsolete in html5, you should be using CSS to do this instead. The u element has not been removed, but itā€™s much better to use CSS for that sort of thing too.

As for the PHP side, if you do have html and php in the same document, itā€™s best to do the PHP at the very start before any html output, so before the <!DOCTYPE>. Things that you want to echo can be stored in a variable for output later, Eg:-

if (mysqli_query($con, $insert)) {
    $message = "Thank you! Your entry was submitted successfully.";
} else {
    $message = "Error: " . $insert . "<br>" . mysqli_error($con);
}

The next point is a security concern.

Putting raw, unsanitised user data into an SQL query is a big no no, as it leaves you open to SQL injection attacks. You need to use prepared statements for this, look it up and ask for help if you get stuck.

1 Like

Thank you so much. I was also concerned with security. Please help with regards to a prepared statement. I donā€™t know anything about prepared statements.

Iā€™ve not used them with mysqli because I use PDO instead, so I donā€™t know exactly.
But you go to resource is the php manual.
https://www.php.net/manual/en/mysqli.prepare.php
Or if you want more detail or something easier to digest a search will find tutorials, for example https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

1 Like

I was able to write this code but it doesnā€™t work. Any help on this would be greatly appreciated.

<?php

include_once 'includes/dhb.php';

?>

 <!DOCTYPE html>
 <html lang="en-us">
   <head>
     <meta charset="utf-8">
     <title>Submit Page</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link rel="stylesheet" type="text/css" href="includes/style.css">

   </head>
   <body>
       <div class="login-box">
       <img src="images/logo.png" class="logo">

<?php

$id = "";
$date = mysqli_real_escape_string ($con, $_POST['date']);
$truckno = mysqli_real_escape_string ($con, $_POST['truckno']);
$diesel = mysqli_real_escape_string ($con, $_POST['diesel']);
$def = mysqli_real_escape_string ($con, $_POST['def']);
$absorbent = mysqli_real_escape_string ($con, $_POST['absorbent']);
$uname = mysqli_real_escape_string ($con, $_SESSION ['username']);

$insert="INSERT INTO consumables (id, date, truckno, diesel, def, absorbent, username) VALUES (?, ?, ?, ?, ?, ?, ?);";

$stmt - mysqli_stmt_init($con);

if (!mysqli_stmt_prepare ($stmt, $insert)) {
    echo "Oops! Something went wrong. Please try again. " . $insert . "<br>" . mysqli_error($con);
} else {
  mysqli_stmt_bind_param ($stmt, "sssssss", NULL, $date, $truckno, $diesel, $def, $absorbent, $uname);
  mysqli_stmt_execute ($stmt);
  echo "Thank you! Your entry was submitted successfully.";
}
?>

   <h2>What would you like to do next?</h2>

<div align="left">
   <a href="consumables.php"><font size="4" color="white"><u>Add More Consumables</u></font></a>
</div>
 <br>
      <form action="logout.php" method="post">
       <input type="submit" name="submit" value="Log Out">


      </form> 
   </body>
 </html>

Donā€™t use mysqli_real_escape_string with prepared statements, they make it redundant.

As I said Iā€™m not familiar with prepared statements in mysqli, so Iā€™m not certain on this, but in examples I have seen the parameters are bound individually. Someone could hopefully clarify this, as Iā€™m not familiar with paramerter binding either, in PDO I insert the values as an array in the execute(), Iā€™m not sure if mysqli can do that.

1 Like

Iā€™m not familiar with PDO. Iā€™ll keep working on it. Thank you for taking the time.

Just looked in the manual and you can bind multiple params at once.

What errors does it report?

The screen goes completely blank. I have also gotten error echoing the $insert statement.

Do you have error reporting enabled? Itā€™s a must for debugging.

Sorry. I donā€™t know how to do that. Iā€™m very new at this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.