Insert Data From a Form Into a Database

Now we will create an HTML form that can be used to add new records to the “Persons” table.

Here is the HTML form:


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


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:

// Check connection
if (mysqli_connect_errno())
echo “Failed to connect to MySQL: ” . mysqli_connect_error();

$sql=”INSERT INTO Persons (FirstName, LastName, Age)

if (!mysqli_query($con,$sql))
die(‘Error: ‘ . mysqli_error($con));
echo “1 record added”;




Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: