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 @ visit and download the sample code:

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:


$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) {

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

I hope this tutorial can help you. Kindly visit here if you want to download this code.

Happy coding :)

Top comments (0)