PHP + MySQL tutorial (4): The MySQLInsertInto insert into statement is used to INSERT a new record INTO the database table.
Insert data to a database table
The insert into statement is used to add a new record to a database table.
Syntax
Insert into table_name
VALUES (value1, value2 ,....)
You can also specify the columns in which 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.
To allow PHP to execute this statement, we must use the mysql_query () function. This function is used to send queries or commands to MySQL connections.
Example
In the previous section, we created a table named "Person" 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 "Person" table:
$ Con = mysql_connect ("localhost", "peter", "abc123 ");
If (! $ Con)
{
Die ('could not connect: '. mysql_error ());
}
Mysql_select_db ("my_db", $ con );
Mysql_query ("insert into person (FirstName, LastName, Age)
VALUES ('Peter ', 'Griffin', '35 ')");
Mysql_query ("insert into person (FirstName, LastName, Age)
VALUES ('Glenn', 'quagmire', '33 ')");
Mysql_close ($ con );
?>
Insert data from the form into the database
Now, we create an HTML form that inserts a new record into the "Person" table.
Here is the HTML form:
When you click the submit button in the HTML form in the preceding example, the form data is sent to "insert. php ". The "insert. php" file connects to the database and retrieves the value from the form using the $ _ POST variable. Then, the mysql_query () function executes the insert into statement, and a new record is added to the database table.
The code for the "insert. php" page is as follows:
$ Con = mysql_connect ("localhost", "peter", "abc123 ");
If (! $ Con)
{
Die ('could not connect: '. mysql_error ());
}
Mysql_select_db ("my_db", $ con );
$ SQL = "INSERT INTO person (FirstName, LastName, Age)
VALUES
('$ _ POST [firstname]', '$ _ POST [lastname]', '$ _ POST [age]') ";
If (! Mysql_query ($ SQL, $ con ))
{
Die ('Error: '. mysql_error ());
}
Echo "1 record added ";
Mysql_close ($ con)
?>