PHP ยท Chapter 42 of 44

PHP PDO Select, Insert, Update, Delete

Once connected with PDO, you can run SQL queries to select, insert, update, and delete data. The query() method is useful for simple SELECT statements, while prepare() and execute() are preferred for queries involving user input.

Fetching results is done with methods like fetch() for a single row or fetchAll() for every matching row, typically returned as associative arrays for easy access by column name.

Syntax
$pdo->query("SELECT ...");
$pdo->exec("INSERT ...");

Selecting data

$pdo->query("SELECT * FROM users")->fetchAll(PDO::FETCH_ASSOC) runs a query and returns all matching rows as an array of associative arrays.

Insert, update and delete

INSERT, UPDATE and DELETE statements are executed with $pdo->exec($sql) or through prepared statements, and typically return the number of affected rows.

Example 1 (php)
<?php
  $stmt = $pdo->query("SELECT name FROM users");
  $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  foreach ($users as $user) {
    echo $user["name"] . " ";
  }
?>
Output
Amy Ben 

fetchAll() with FETCH_ASSOC returns each row as an associative array keyed by column name.

Example 2 (php)
<?php
  $rows = $pdo->exec("UPDATE users SET active = 1 WHERE id = 1");
  echo "$rows row(s) updated";
?>
Output
1 row(s) updated

exec() runs an UPDATE statement and returns the number of rows that were changed.

Key points

  • query() is used for simple SELECT statements without user input.
  • exec() runs INSERT, UPDATE or DELETE statements and returns affected row count.
  • fetch() retrieves a single row; fetchAll() retrieves all matching rows.
  • PDO::FETCH_ASSOC returns rows as associative arrays keyed by column name.
๐Ÿ’ก Note: Never build SQL queries by directly concatenating user input โ€” use prepared statements instead to avoid SQL injection.

๐Ÿ“ Quick Quiz

1. Which method returns all matching rows from a query?

2. Which method is typically used to run INSERT/UPDATE/DELETE statements?

3. What does PDO::FETCH_ASSOC produce?