Table of contents

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,...)

 

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

 

I hope it helps. Thank you for reading :)