How to access mysql result set data with a foreach loop

How to access mysql result set data with a foreach loop

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Iterating Over Multidimensional MySQL Result Sets

You have a multidimensional array returned by your database class, where each element is an associative sub-array containing id, firstname, and lastname. You want to iterate over this data using a foreach loop. The confusion often arises because you're thinking of nested loops when the structure is already flat at the top level.

The key insight is that your result set is an array of arrays. The outer array contains rows, and each row is itself an associative array representing a record. You can iterate directly over the outer array using foreach, and inside that loop, access the fields of each row as properties or array keys.

Direct Iteration with foreach

Here's how to use foreach correctly on this structure:

$results = $db->select('SELECT * FROM users'); // Returns multidimensional array

foreach ($results as $row) {
    echo $row['id'];
    echo ' - ';
    echo $row['firstname'];
    echo ' - ';
    echo $row['lastname'] . "<br>";
}

In this example, $row holds each record from the result set. You don't need nested foreach loops unless you're dealing with a multidimensional structure like an array of arrays where each inner array itself contains multiple rows (e.g., categories with items). In your case, each row is already associative and ready for direct access.

Why This Works

PHP arrays are flexible structures. When you use foreach ($results as $row), PHP iterates over the top-level keys (0, 1, 2, etc.), assigning each sub-array to $row. Inside the loop, $row behaves like any other associative array, so you can access fields using bracket notation ($row['firstname']) or dot notation if you convert it to an object.

This approach is efficient and doesn't introduce unnecessary overhead. There's no performance penalty for accessing associative arrays inside a foreach loop—it's the standard way to process result sets in PHP.

Converting to Objects (Optional)

If you prefer working with objects instead of arrays, you can convert each row using stdClass:

foreach ($results as $row) {
    $user = (object) $row;
    echo $user->id . ' - ' . $user->firstname . ' ' . $user->lastname . "<br>";
}

This makes the code slightly more readable and allows you to use property access instead of array keys. However, it adds a small overhead during conversion, so only do this if object syntax improves clarity or if your application already relies on object-oriented data handling.

Avoiding Nested Loops Unless Necessary

A common misconception is that iterating over multidimensional arrays requires nested loops. That's only true if the structure itself is nested—like an array of categories, where each category contains a list of items. In your case, the structure is flat: one level of rows, each being an associative array. Adding nested foreach loops would indeed increase complexity and potentially slow down execution, but it's not needed here.

Best Practices in Modern PHP

While your database class works for basic queries, note that the tutorial you referenced uses outdated practices like direct SQL execution without prepared statements and legacy MySQL functions. If you're starting a new project or refactoring existing code, consider using PDO or MySQLi with parameterized queries to prevent SQL injection and improve maintainability.

For example, with PDO:

$stmt = $pdo->query("SELECT id, firstname, lastname FROM users");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

This pattern gives you the same multidimensional array structure but with better security and flexibility.

If you're working within a Laravel ecosystem, you might find that Eloquent ORM handles result sets differently, returning collections of models rather than raw arrays. For more details on integrating database interactions in Laravel projects, see https://laravelcompany.com.

Our network