How do I perform CRUD operations with PDO?

Performing CRUD (Create, Read, Update, Delete) operations using PHP Data Objects (PDO) is essential for interacting with a database securely and efficiently. Below is a simple demonstration of how these operations can be carried out using PDO.

This example showcases how to connect to a database, insert new records, retrieve existing records, update records, and delete records using PDO in PHP.

PHP, PDO, CRUD operations, database interaction, secure database access

<?php // Database connection $host = '127.0.0.1'; $db = 'my_database'; $user = 'my_user'; $pass = 'my_password'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } // Create $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->execute(['John Doe', 'john@example.com']); // Read $stmt = $pdo->query("SELECT * FROM users"); $users = $stmt->fetchAll(); foreach ($users as $user) { echo $user['name'] . '<br>'; } // Update $stmt = $pdo->prepare("UPDATE users SET email = ? WHERE name = ?"); $stmt->execute(['john.doe@example.com', 'John Doe']); // Delete $stmt = $pdo->prepare("DELETE FROM users WHERE name = ?"); $stmt->execute(['John Doe']); ?>

PHP PDO CRUD operations database interaction secure database access