DEV Community

Cover image for PHP PDO Insert Multiple Rows Example
Code And Deploy
Code And Deploy

Posted on

PHP PDO Insert Multiple Rows Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/php-pdo-insert-multiple-rows-example

In this post, I'm sharing an example of how to insert records in PHP PDO in multiple rows. If you have a task on saving multiple records then this is for you. All you need is to set up your database and table.

In this example, I'm using an array that consists of records for each row. See below code of PHP PDO multiple insert example:

<?php

$host     = 'localhost';
$db       = 'demos';
$user     = 'root';
$password = '';

$dsn = "mysql:host=$host;dbname=$db;charset=UTF8";

try {
     $conn = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

} catch (PDOException $e) {
     echo $e->getMessage();
}

$data = [
     [
          'title' => 'test title 1',
          'content' => 'test content 1'
     ],
     [
          'title' => 'test title 2',
          'content' => 'test content 2'
     ],
     [
          'title' => 'test title 3',
          'content' => 'test content 3'
     ]
];

$sql = 'INSERT INTO posts(title, content) VALUES(:title, :content)';

$statement = $conn->prepare($sql);

foreach($data as $row) {
    $statement->execute($row); 
}

echo "Posts saved successfully!";
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/php-pdo-insert-multiple-rows-example if you want to download this code.

Happy coding :)

Top comments (2)

Collapse
 
cristianh033 profile image
Cristian David Home

Please don't do that!

Collapse
 
rodbas profile image
Rod Bas • Edited

Please, never do that!!!!

Some solution