0
0
PHPprogramming~5 mins

Fetch modes and styles in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Fetch modes and styles
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The while loop fetching each row from the database.
  • How many times: Once for each row in the result set (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 calls
100100 fetch calls
10001000 fetch calls

Pattern observation: The number of operations grows directly with the number of rows.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[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.

Interview Connect

Understanding how fetching data scales helps you write efficient database code and shows you know how to handle growing data smoothly.

Self-Check

"What if we changed fetch mode to fetch all rows at once with fetchAll()? How would the time complexity change?"