Tags
Asked 3 years ago
17 Jun 2021
Views 294
Roscoe

Roscoe posted

Multiple mysql INSERT statements in one query php

Multiple mysql INSERT statements in one query php
jaggy

jaggy
answered Apr 28 '23 00:00

Sure, here's a rewrite:

You can use the MULTI- INSERT syntax in PHP to perform multiple MySQL INSERT statements in a single query. Here's an example:



INSERT INTO mytable (column1, column2, column3)
VALUES ('value1', 'value2', 'value3'),
       ('value4', 'value5', 'value6'),
       ('value7', 'value8', 'value9');

In this example, mytable is the name of the table, and c olumn1, column2, and column3 are the names of the columns that the values will be inserted into. The VALUES keyword is followed by multiple value sets enclosed in parentheses, separated by commas. Each value set corresponds to a row that will be inserted into the table.

To execute this query in PHP using the PDO extension, you can prepare the query using PDO::prepare() and execute it using PDOStatement::execute(). Here's an example:



$dbh = new PDO("mysql:host=localhost;dbname=mydatabase", $user, $pass);

$stmt = $dbh->prepare("INSERT INTO mytable (column1, column2, column3)
                       VALUES (?, ?, ?),
                              (?, ?, ?),
                              (?, ?, ?)");

$stmt->execute(array('value1', 'value2', 'value3',
                     'value4', 'value5', 'value6',
                     'value7', 'value8', 'value9'));

In this example, PDO::prepare() is used to prepare the query with placeholders for the values to be inserted. The execute () method is then called with an array of values as a parameter, which corresponds to the placeholders in the query.

Note that while the MULTI-INSERT syntax can be more efficient than executing multiple INSERT statements separately, it's important to be aware of any limits on the size of a single query that may be imposed by your database server or network.
Post Answer