Php inserts data into a database with empty values ​​before submitting the form?

I am trying to use this code from , which inserts empty fields into the database when the page loads, and then if the form fields are filled in and the request is sent, then it sends another batch of data to the database (MySQL).

<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html> 
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

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

mysqli_close($con);
?> 
+3
source share
3 answers
<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit" name="submit" value="submit" />
</form>

</body>
</html> 
<?php
if($_POST['submit']){
  $con=mysqli_connect("example.com","peter","abc123","my_db");
  // Check connection
  if (mysqli_connect_errno())
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql="INSERT INTO Persons (FirstName, LastName, Age)
      VALUES
      ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

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

  mysqli_close($con);
}
?> 

You should check if the variable ($ _ POST ['submit']) has a value.

also you need to add some value and name to your input type = "submit" html element

<input type="submit" name="submit" value="Submit!" />
+4
source

You need to check isset()your submit button before pasting, otherwise it will insert a blank line at each boot, so add it

</body>
</html> 
<?php

if(isset($_POST['submit']))
{
     $con=mysqli_connect("example.com","peter","abc123","my_db");

     //all your code here
}

, ,

<input type"submit" name="submit">
+2

jn if:

(isset ($ _ post)) {    }

+1

All Articles