Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function mysql_query.The INSERT INTO statement is used to insert new records in a table.
Insert Data Into a Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name |
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,…) |
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statements above we must use the mysqli_query() function. This function is used to send a query or command to a MySQL connection.
Example
In the previous chapter we created a table named "Persons", with three columns; "FirstName", "LastName" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table:
<?php
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
mysqli_close($con); |
PHP 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:
<html>
<form action="insert.php" method="post">
</body> |
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
$sql="INSERT INTO Persons (FirstName, LastName, Age)
if (!mysqli_query($con,$sql))
mysqli_close($con); |
Example:
Try out following example to insert record into employee table.
<?php
mysql_select_db('test_db'); |
In real application, all the values will be taken using HTML form and then those values will be captured using PHP script and finally they will be inserted into MySQL tables.
While doing data insert its best practice to use function get_magic_quotes_gpc() to check if current configuration for magic quote is set or not. If this function returns false then use function addslashes() to add slashes before quotes.
Example:
Try out this example by putting this code into add_employee.php, this will take input using HTML Form and then it will create records into database.
<html>
if(! get_magic_quotes_gpc() )
$sql = "INSERT INTO employee ". |