PHP-MySQL Lesson: Insert records

Insert records

In this lesson we are going to write a PHP script that inserts a new record in our database through HTML forms.

The INSERT INTO statement in sql is used to insert a record in the database. In PHP, mysql_query() function is used to execute INSERT INTO query. We can execute any sql query like insert, update, delete, select etc. using the mysql_query() function.

We need two pages here namely the insert.php and the insertform.php or insertform.html.On our insertform.html we are going to create a form to collect the data entered by the user.

Here is the code:

<html> <head><title>Test Page</title></head>
<body> 
<form action="insert.php" method="post">
First name: <input type="text" name="fname">
Last name: <input type="text" name="lname">
Position: <input type="text" name="position">
Age: <input type="text" name="age">
Salary: <input type="text" name="salary">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

</body>
</html> 

This page will submit the First name, Last name, Position, Age, Salary, Email data to the page process.php when the submit button is clicked.

Now we are going to create the insert.php file.

Here is the code:

<?php
//including the database connection file
include("mysql_connect.php");
$sql="INSERT INTO employee_record (f_name, l_name, position,age,salary,email)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[position]','$_POST[age]','$_POST[salary]','$_POST[email]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>

In our example we have used include() function, this function takes all the content in a specified file and includes it in the current file. Then we have declared $sql variable that will handle the sql statement. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the employee_record table.

, , , , ,

Post navigation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.