Home  >  Article  >  Database  >  How to Insert Multiple Rows into a Database with PDO Prepared Statements?

How to Insert Multiple Rows into a Database with PDO Prepared Statements?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 21:48:02335browse

How to Insert Multiple Rows into a Database with PDO Prepared Statements?

Inserting Multiple Rows with PDO Prepared Statements

Inserting multiple rows into a database using a single prepared statement is not only possible but also recommended for its efficiency and security.

Approach with a Single Insert Query

The first method involves using a single INSERT query with multiple values:

INSERT INTO Table (col1, col2, col3) 
VALUES ('abc', 'def', 'ghi'),
       ('abc', 'def', 'ghi'),
       ('abc', 'def', 'ghi'),
       ('abc', 'def', 'ghi'),
       ('abc', 'def', 'ghi')
       -- and so on...

To execute this query using PDO, you can follow these steps:

$query = "INSERT INTO Table (col1, col2, col3) 
VALUES (?, ?, ?),
       (?, ?, ?),
       (?, ?, ?)
";
$params = array('abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi');
$stmt = DB::getInstance()->prepare($query);
$stmt->execute($params);

Approach with Individual Insert Queries

If the number of rows to be inserted is too large, you may need to execute individual insert queries:

$query = "INSERT INTO Table (col1, col2, col3) VALUES (".implode(',', $args).")";
$stmt = $pdo->prepare($query);

foreach ($rows as $row) 
{
   $stmt->execute($row);
}

This approach ensures that each row is inserted separately, minimizing the risk of issues during insertion.

Conclusion

Whether you use a single insert query with multiple values or individual insert queries, PDO prepared statements provide efficient and secure methods for inserting multiple rows into a database. Choosing the right approach depends on the specific requirements of the application and database.

The above is the detailed content of How to Insert Multiple Rows into a Database with PDO Prepared Statements?. 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