Fetch modes and styles in PHP - Time & Space Complexity
When fetching data from a database in PHP, the way we get results affects how long it takes.
We want to know how the time to fetch data grows as the amount of data increases.
Analyze the time complexity of the following code snippet.
// Fetch all rows as associative arrays
$stmt = $pdo->query('SELECT * FROM users');
$results = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
This code fetches all rows from a users table one by one as associative arrays and stores them in an array.
- Primary operation: The while loop fetching each row from the database.
- How many times: Once for each row in the result set (n times).
Each row requires one fetch operation, so the total work grows as the number of rows grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 fetch calls |
| 100 | 100 fetch calls |
| 1000 | 1000 fetch calls |
Pattern observation: The number of operations grows directly with the number of rows.
Time Complexity: O(n)
This means the time to fetch all rows grows linearly with the number of rows.
[X] Wrong: "Fetching all rows at once is always faster than fetching one by one."
[OK] Correct: Fetching all at once may use more memory and sometimes the fetch loop is just as efficient because it processes rows as they come.
Understanding how fetching data scales helps you write efficient database code and shows you know how to handle growing data smoothly.
"What if we changed fetch mode to fetch all rows at once with fetchAll()? How would the time complexity change?"