DEV Community

Cover image for PHP PDO Insert Tutorial Example
Code And Deploy
Code And Deploy

Posted on

PHP PDO Insert Tutorial Example

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

In this post, I'm sharing a simple PHP PDO insert, create, save record tutorial example. If you are new to PHP we have many available functions on saving to the database with PHP we can you the method of MySQLi Object-Oriented, MySQLi Procedural, then PDO which we tackle in this post.

Take note that before saving to your database you must double-check and validate the data if clean and prevent the potential SQL Injection.

MySQL Insert

Anyway, let's continue. When doing an insert statement with MySQL the below code will show like this:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Enter fullscreen mode Exit fullscreen mode

PHP PDO & MySQL Insert

But when PHP & MySQL interacting with each other on saving records to our database this it should be like this:

<?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',
     'content' => 'test content'
];

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

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

$statement->execute($data);

echo "Post 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-tutorial-example if you want to download this code.

Happy coding :)

Discussion (0)