In the above case, when a user clicks the "submit" button in the HTML form, the data in the form will be sent to "insert. php ". "Insert. the php file is connected to the database and the data in the form is obtained using the PHP $ _ POST variable. in this case, the mysql_query () function implements the "INSERTINTO" statement, A new record is added to the database
The insert into statement inserts a new record INTO a database table.
Insert data into a database table
"Insert into" is used to INSERT a new record INTO a database table.
Syntax
Insert into table_name
VALUES (value1, value2 ,....)
You can insert data into the specified column as follows:
Insert into table_name (column1, column2 ,...)
VALUES (value1, value2 ,....)
Note: SQL statements are "case-insensitive" statements (which do not distinguish between uppercase and lowercase letters), that is, "INSERT INTO" and "insert into" are the same.
To create a database in PHP, we need to apply the above statement in the mysql_query () function. This function is used to send the request and command for establishing a MySQL database connection.
Case
In the previous chapter, we created a table named "Person", which contains three columns: 'firstname', 'lastname', and 'age '. In the following case, we will use the same table and add two new records:
$ 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 ', 'grigin', '35')'); mysql_query ('Insert INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'quagmire', '33') '); mysql_close ($ con );
?>
Insert data from a table into the database
Now we will create an HTML form with which we can add new records to the "Person" table.
The following shows the HTML form:
In the above case, when a user clicks the "submit" button in the HTML form, the data in the form will be sent to "insert. php ". "Insert. the php file is connected to the database and the data in the form is obtained using the PHP $ _ POST variable. in this case, the mysql_query () function executes the insert into statement, A new record is added to the database form.
Code of the "insert. php" page:
$ 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)
?>