0
0
PHPprogramming~5 mins

Fetching results (fetch, fetchAll) in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Fetching results (fetch, fetchAll)
O(n)
Understanding Time Complexity

When we get data from a database in PHP, we often use fetch or fetchAll to retrieve rows. Understanding how long these operations take helps us write faster programs.

We want to know: how does the time to get results grow as the number of rows grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Assume $stmt is a prepared PDO statement
$stmt->execute();

// Fetch one row at a time
while ($row = $stmt->fetch()) {
    // process $row
}

// Or fetch all rows at once
$allRows = $stmt->fetchAll();

This code fetches rows from a database query, either one by one or all at once.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Fetching each row from the database result set.
  • How many times: Once for each row in the result (n times).
How Execution Grows With Input

Each row requires one fetch operation, so the total work grows as the number of rows grows.

Input Size (n)Approx. Operations
1010 fetch operations
100100 fetch operations
10001000 fetch operations

Pattern observation: The time grows directly with the number of rows; double the rows, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to fetch results grows linearly with the number of rows returned.

Common Mistake

[X] Wrong: "Fetching all rows at once is always faster than fetching one by one."

[OK] Correct: Fetching all rows uses more memory and can be slower if the result set is very large. Both methods still take time proportional to the number of rows.

Interview Connect

Understanding how fetching data scales helps you write efficient database code, a skill useful in many real projects and interviews.

Self-Check

"What if we used fetchAll but limited the query to only 10 rows? How would the time complexity change?"