Home >Backend Development >PHP Tutorial >How to Insert Multiple Rows in a MySQL Table with a Single Query?

How to Insert Multiple Rows in a MySQL Table with a Single Query?

Barbara Streisand
Barbara StreisandOriginal
2024-11-22 22:57:13967browse

How to Insert Multiple Rows in a MySQL Table with a Single Query?

How to Perform Multiple Row Insertion with a Single MySQL Query

In web development, it is often necessary to insert multiple rows of data into a database table at once. MySQL provides a convenient way to accomplish this using a single query.

Problem:

Suppose you have an HTML form that allows users to enter a quantity of items to be registered. You have a MySQL query that you want to execute to insert each registered user into a database table. The challenge is to execute this query multiple times, corresponding to the specified quantity.

Solution:

The solution is to use the MySQL INSERT statement with multiple VALUE clauses. This allows you to specify multiple rows of data to insert in a single query.

INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

In this example, the INSERT statement will insert three rows into the table with the following values:

  • Row 1: (a=1, b=2)
  • Row 2: (a=2, b=3)
  • Row 3: (a=3, b=4)

You can easily modify the query to insert the specified quantity of rows by dynamically setting the number of VALUE clauses.

By using this approach, you can efficiently insert multiple rows of data into a MySQL table with a single query. This can significantly improve performance compared to executing multiple INSERT statements individually.

Additional Resources:

  • [MySQL INSERT Documentation](http://dev.mysql.com/doc/refman/5.5/en/insert.html)

The above is the detailed content of How to Insert Multiple Rows in a MySQL Table with a Single Query?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn