PHP MySQL Insert Into
- Previous Page MySQL Create
- Next Page MySQL Select
The INSERT INTO statement is used to insert new records into a database table.
Inserting data into a database table
The INSERT INTO statement is used to add new records to a database table.
Syntax
INSERT INTO table_name VALUES (value1, value2,...)
You can also specify the columns where you want to insert data:
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)
Note:SQL statements are case-insensitive. INSERT INTO is the same as insert into.
To make PHP execute this statement, we must use the mysql_query() function. This function is used to send queries or commands to a MySQL connection.
Example
In the previous chapters, 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 $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?>
Inserting data from the form into the database
Now, we create an HTML form that can insert new records into the "Persons" table.
This 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 the user clicks the submit button in the HTML form in the above example, the form data is sent to "insert.php". The "insert.php" file connects to the database and retrieves values from the form through the $_POST variable. Then, the mysql_query() function executes the INSERT INTO statement, and a new record is added to the database table.
The following is the code for the "insert.php" page:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?>
- Previous Page MySQL Create
- Next Page MySQL Select