Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:

<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>

When a user clicks the submit button in the HTML form, in the example above, the form data is sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables.
Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table.
Here is the "insert.php" page:

<?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);
?>

2 comments:

  1. you are doing well giving us a lot of knowledge about every aspect of PHP...
    check...
    Insert Php Code

    ReplyDelete
  2. Good post! Just one question, when I place the insert.php in public_html folder, I get the message Page not found. Nothing could be found here.

    Any idea why?

    Thanks
    David

    ReplyDelete

 
Top
Blogger Template