This article mainly introduces the use of InsertInto data insertion in PHP + MySQL. The example analyzes the related skills of php + mysql for data insertion based on InsertInto statements, which has some reference value, for more information about how to Insert Into data in PHP + MySQL, see the following example. Share it with you for your reference. The details are as follows:
The insert into statement is used to INSERT a new record INTO a 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_nameVALUES (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 "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);?>
Insert data from the form into the database:
Now, we create an HTML form that inserts a new record into the "Persons" 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:
<?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('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";if (!mysql_query($sql,$con)){ die('Error: ' . mysql_error());}echo "1 record added";mysql_close($con)?>
I hope this article will help you with php programming.