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 = $connection->prepare("INSERT INTO `posts` SET `id`=?, `title`=?, `date`=?");
$create->execute(array($id, $title, $date));

$update = $connection->prepare("UPDATE `posts` SET `title`=?, `date`=? WHERE `id`=$id");
$update ->execute(array($title, $date));

$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 / update / delete / crud / mysql / pdo

← Simple Select Query with PDO Remove Empty Lines In SublimeText →