0Pricing
PHP Academy · Lesson

Working with PDO

Use PHP Data Objects (PDO) to interact with databases.

Working with PDO is a free PHP Academy lesson on CoddyKit — lesson 6 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Working with PDO

Welcome to the next lesson! In this lesson, you’ll learn how to use PDO (PHP Data Objects) for database interaction. PDO is a flexible and secure way to connect and work with databases. Let’s dive in!

Working with PDO — illustration 1

2

What Is PDO?

PDO (PHP Data Objects) is a database access layer that provides a uniform interface for working with different database systems. It supports a variety of databases like MySQL, PostgreSQL, SQLite, and more.

Key Features:

  • Database independence (works with multiple database types).
  • Built-in support for prepared statements.
  • Advanced error handling options.

Tip: PDO is a great choice for building secure and scalable web applications.

3

Connecting to a Database with PDO

To connect to a database using PDO, you need:

  • The Data Source Name (DSN), including the database type, host, and name.
  • A valid username and password.

Example:

Tip: Use environment variables or configuration files for sensitive credentials.

<?php
  $dsn = "mysql:host=localhost;dbname=testdb";
  $username = "root";
  $password = "";

  try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!";
  } catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
  }
?>

4

Executing Queries

PDO provides two main methods for executing queries:

  • exec(): For statements that don’t return results (e.g., INSERT, UPDATE).
  • query(): For statements that return results (e.g., SELECT).

Example:

<?php
  // Insert a record
  $pdo->exec("INSERT INTO users (name, email) VALUES ('Alice', 'alice@mail.com')");

  // Retrieve records
  $stmt = $pdo->query("SELECT * FROM users");
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";
  }
?>

5

Using Prepared Statements

Prepared statements are essential for secure and efficient database interaction. Example:

Tip: Use placeholders (:email) to prevent SQL injection.

<?php
  $sql = "SELECT * FROM users WHERE email = :email";
  $stmt = $pdo->prepare($sql);
  $stmt->execute(["email" => "alice@mail.com"]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);

  echo "Name: " . $user["name"];
?>

6

Error Handling in PDO

PDO supports three error handling modes:

  • ERRMODE_SILENT: Errors must be manually checked.
  • ERRMODE_WARNING: Errors trigger PHP warnings.
  • ERRMODE_EXCEPTION: Errors throw exceptions (recommended).

Example:

<?php
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  try {
    $pdo->exec("INVALID SQL STATEMENT");
  } catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
  }
?>

7

Fetching Data

PDO provides several fetching methods:

  • fetch(): Retrieves a single row.
  • fetchAll(): Retrieves all rows.
  • fetchColumn(): Retrieves a single column value.

Example:

<?php
  $stmt = $pdo->query("SELECT name FROM users");
  while ($name = $stmt->fetchColumn()) {
    echo "User: " . $name . "<br>";
  }
?>

8

Transaction Management

Use transactions for executing multiple queries as a single unit. Example:

Tip: Use transactions to ensure data integrity.

<?php
  try {
    $pdo->beginTransaction();

    $pdo->exec("INSERT INTO users (name, email) VALUES ('Bob', 'bob@mail.com')");
    $pdo->exec("INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@mail.com')");

    $pdo->commit();
    echo "Transaction successful!";
  } catch (PDOException $e) {
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
  }
?>

9

10

Great Job!

Congratulations! You’ve learned how to use PDO for secure and efficient database interaction, including connecting, executing queries, and managing transactions. In the next lesson, we’ll explore advanced SQL querying techniques with PDO. Let’s keep coding!

Working with PDO — illustration 10

Frequently asked questions

Is the “Working with PDO” lesson free?

Yes — the full text of “Working with PDO” is free to read here on the web, and the PHP Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Working with PDO”?

Use PHP Data Objects (PDO) to interact with databases. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 6 of 6, so you can start here or from the beginning and move at your own pace.

How long does the “Working with PDO” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Databases
  2. Connecting to a MySQL Database
  3. Managing Tables
  4. Performing CRUD Operations
  5. Prepared Statements
  6. Working with PDO
← Back to PHP Academy