DEV Community

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

Posted on

4 2

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 :)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

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

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay