Home >Backend Development >PHP Tutorial >How to Insert Multiple Rows into a MySQL Table with a Single Query?
Inserting Multiple Rows with a Single MySQL Query
Inserting multiple rows into a MySQL table with a single query is often necessary to optimize database operations and reduce overhead. Consider the following scenario:
Problem:
You need to insert a large number of user registrations into a pxlot table. The user information is captured through an HTML form that includes a quantity input, specifying the number of times a particular registration query needs to be executed.
Solution:
To insert the registration query multiple times, you can use a MySQL INSERT statement that includes multiple sets of values within a single query:
INSERT INTO `pxlot` (realname, email, address, phone, status, regtime, ip) VALUES ('$realname', '$email', '$address', '$phone', '0', '$dateTime', '$ip'), ('anotherRealname', 'anotherEmail', 'anotherAddress', 'anotherPhone', '0', '$anotherDateTime', '$anotherIp'), ('thirdRealname', 'thirdEmail', 'thirdAddress', 'thirdPhone', '0', '$thirdDateTime', '$thirdIp');
This statement inserts three rows into the pxlot table. Each row represents a separate user registration and is enclosed within its own set of parentheses.
Note: The number of value sets within the INSERT statement determines the number of rows inserted. For instance, if you need to insert 30 rows, you would include 30 sets of values within the statement.
By using this multiple value insertion method, you can significantly improve the performance and efficiency of your database operations.
The above is the detailed content of How to Insert Multiple Rows into a MySQL Table with a Single Query?. For more information, please follow other related articles on the PHP Chinese website!