PHP · PHP Intermediate

PHP and PDO

Run this in the Online PHP compiler

Hello, budding PHP developers!

Delve deeper into the world of PHP with the PHP Data Objects (PDO). PDO offers a unified interface for accessing databases in PHP, ensuring flexibility and security. So, let's explore PDO!

Why PDO?

  • Database Agnostic: PDO is versatile and can work with a variety of database systems without requiring changes to your code.
  • Prepared Statements: With PDO, you can use prepared statements, bolstering your application's defense against SQL injection attacks.

Key Points

Connecting to a Database: With PDO, connecting to a database becomes simple:
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
try {
    $conn = new PDO($dsn, $username, $password);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

CRUD Operations using PDO

  • Create:  Insert new records into the database.
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
  • Read: Retrieve specific records or fetch all records from the database.
$stmt = $conn->prepare("SELECT name, email FROM users");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
    echo $row['name'] . " - " . $row['email'] . "";
}
  • Update: Modify or change existing records in the database based on certain conditions.
$stmt = $conn->prepare("UPDATE users SET email=:email WHERE name=:name");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $updatedEmail);
$stmt->execute();
  • Delete: Remove specific records from the database.
$stmt = $conn->prepare("DELETE FROM users WHERE name=:name");
$stmt->bindParam(':name', $name);
$stmt->execute();

Exercise

Now let’s Jdoodle it!

  • Create a connection using PDO.
  • Add a few entries using prepared statements.
  • Display these entries.
  • Update and delete some records.

Conclusion

Mastering PDO will enhance your proficiency in handling database operations in PHP. With PDO, you're not just coding; you're crafting secure and efficient database interactions. Practice and explore the myriad functionalities PDO offers, and soon you'll be a PDO maestro!

This website uses cookies to ensure you get the best experience on our website.