CRUD (Create, Read, Update, Delete) operations are fundamental when working with databases. In this guide, we'll explore how to perform these operations using PHP and PDO (PHP Data Objects), a database abstraction layer that provides a consistent interface for database interactions.
Connecting to the Database
To get started with PDO, you need to establish a database connection. Here's an example of how to connect to a MySQL database:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO(`mysql:host=$host;dbname=$dbname`, $username, $password);
echo `Connected to the database`;
} catch (PDOException $e) {
die(`Error: ` . $e->getMessage());
}
?>
Creating Records (Create - INSERT)
To insert data into the database, you can use the
INSERT statement. Here's an example of how to create a new record: <?php
$name = 'John Doe';
$email = 'john@example.com';
$stmt = $pdo->prepare(`INSERT INTO users (name, email) VALUES (?, ?)`);
$stmt->execute([$name, $email]);
echo `Record created successfully`;
?>
Reading Records (Read - SELECT)
To retrieve data from the database, you can use the
SELECT statement. Here's an example of how to read records: <?php
$stmt = $pdo->query(`SELECT * FROM users`);
while ($row = $stmt->fetch()) {
echo `Name: ` . $row['name'] . `, Email: ` . $row['email'] . `<br>`;
}
?>
Updating Records (Update - UPDATE)
To modify existing data, you can use the
UPDATE statement. Here's an example of how to update a record: <?php
$newEmail = 'new_email@example.com';
$userId = 1;
$stmt = $pdo->prepare(`UPDATE users SET email = ? WHERE id = ?`);
$stmt->execute([$newEmail, $userId]);
echo `Record updated successfully`;
?>
Deleting Records (Delete - DELETE)
To remove data from the database, you can use the
DELETE statement. Here's an example of how to delete a record: <?php
$userId = 1;
$stmt = $pdo->prepare(`DELETE FROM users WHERE id = ?`);
$stmt->execute([$userId]);
echo `Record deleted successfully`;
?>
Conclusion
PHP CRUD operations with PDO provide a powerful way to interact with databases. Whether you're creating, reading, updating, or deleting records, PDO simplifies the process while maintaining security and reliability in your database interactions.
