iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

MySQL Select Data

Reading is what apps do most. PDO gives you several ways to fetch results — pick the one that fits how you'll use them.

Query without parameters

PHP
foreach ($pdo->query('SELECT id, name FROM customers') as $row) {
    echo $row['id'], ' ', $row['name'], PHP_EOL;
}

Query with parameters — always preferred for user input

PHP
$stmt = $pdo->prepare('SELECT id, name FROM customers WHERE active = ?');
$stmt->execute([1]);

foreach ($stmt as $row) {
    echo $row['name'], PHP_EOL;
}

Fetch one row

PHP
$stmt = $pdo->prepare('SELECT * FROM customers WHERE id = ?');
$stmt->execute([42]);

$user = $stmt->fetch();   // associative array, or false if no rows

Fetch everything

PHP
$rows = $pdo->prepare('SELECT id, name FROM customers')
            ->fetchAll();
// or: $pdo->query(...)->fetchAll(PDO::FETCH_ASSOC);

Fetch a single value

PHP
$count = $pdo->query('SELECT COUNT(*) FROM customers')->fetchColumn();

Fetch as objects of a class

PHP
class Customer { public int $id; public string $name; }

$rows = $pdo->query('SELECT id, name FROM customers')
            ->fetchAll(PDO::FETCH_CLASS, Customer::class);

foreach ($rows as $c) { echo $c->name; }

Streaming big results

Don't fetchAll() on a million-row result — iterate instead:

PHP
$stmt = $pdo->query('SELECT * FROM big_table');
foreach ($stmt as $row) {
    process($row);
}
Tip: Don't SELECT * in production code. List the columns you actually use — your query is more efficient and survives schema additions intact.

Example

Example
<?php
$rows = $pdo->query('SELECT id, name, email FROM customers')->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    echo $row['id'], ' ', $row['name'], PHP_EOL;
}
Try it Yourself »

Exercise

Fetch every row as an associative array list.

$stmt-> ()

Test yourself

Q1. fetch() with no rows returns…
Q2. Hydrate rows into a class with…
Q3. SELECT * is…

Discussion

Loading…