Home >Database >Mysql Tutorial >How Can I Insert Multiple Rows into a MySQL Table with a Single Query?

How Can I Insert Multiple Rows into a MySQL Table with a Single Query?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 15:23:12600browse

How Can I Insert Multiple Rows into a MySQL Table with a Single Query?

Multiple Row Insertion in MySQL with a Single Query

You have expressed a need to perform multiple insertions into a MySQL table with a single query. This can be achieved efficiently using the following steps:

  1. Construct the Query:

    • You need to build a MySQL "INSERT" query with multiple rows of data.
    • Use the following syntax:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...), (value3, value4, ...), ...;
  1. Specify Multiple Rows:

    • In the "VALUES" section of the query, list the values for each row you want to insert.
    • Separate the rows by commas, as shown in the example below:
INSERT INTO pxlot (realname, email, address, phone, status, regtime, ip)
VALUES ('realname1', 'email1', 'address1', 'phone1', 0, 'dateTime1', 'ip1'),
       ('realname2', 'email2', 'address2', 'phone2', 0, 'dateTime2', 'ip2'),
       ('realname3', 'email3', 'address3', 'phone3', 0, 'dateTime3', 'ip3');
  1. Execute the Query:

    • After constructing the query, you can use the mysql_query() function to execute it.
    • If the insertion is successful, it will return true. Otherwise, it will return false and provide an error message.

Example:

$query = "INSERT INTO pxlot (realname, email, address, phone, status, regtime, ip)
VALUES ('realname1', 'email1', 'address1', 'phone1', 0, 'dateTime1', 'ip1'),
       ('realname2', 'email2', 'address2', 'phone2', 0, 'dateTime2', 'ip2'),
       ('realname3', 'email3', 'address3', 'phone3', 0, 'dateTime3', 'ip3');";

$result = mysql_query($query);
if ($result) {
  echo "Data inserted successfully.";
} else {
  echo "Error: " . mysql_error();
}

The above is the detailed content of How Can I Insert Multiple Rows into 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