Table of contents

PHP PDO Insert Multiple Rows

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!";