Amit Dhamu

Software Engineer

CRUD Functions with PDO

Here is an example of how to perform CRUD (Create, Update, Delete) functions using PDO

$connection = new PDO('mysql:host=localhost;dbname=database1', $username, $pass);

$id = 10;
$title = 'CRUD using PDO';
$date = now();

// CREATE
$create = $connection->prepare('INSERT INTO `posts` SET `id`=?, `title`=?, `date`=?');
$create->execute([$id, $title, $date]);

// UPDATE
$update = $connection->prepare('UPDATE `posts` SET `title`=?, `date`=? WHERE `id`=$id');
$update ->execute([$title, $date]);

// DELETE
$delete = $connection->exec('DELETE FROM posts WHERE id=$id');

The use of the question marks in this function demonstrate the use of unnamed placeholders. You can alternatively use named placeholders for a similar effect. Quick example would be:

$create = $connection->prepare('INSERT INTO `posts` SET `id`=:id, `title`=:title, `date`=:date');
$create->bindParam(':id', $id);
$create->bindParam(':title', $title);
$create->bindParam(':date', $date);
$create->execute();

 create / update / delete / crud / mysql / pdo

Scroll To PositionPDO Database Connection

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.