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']);
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?