Home >Backend Development >PHP Tutorial >How do I access all results in a MySQLi result set instead of just the first one?

How do I access all results in a MySQLi result set instead of just the first one?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 19:02:03721browse

How do I access all results in a MySQLi result set instead of just the first one?

How to Access Results in a MySQLi Result Set

Your query:

select uid from userbase 

Your loop:

$i = 0;
$output = mysqli_query($mysqli, "select uid from userbase");
while ($row = $output->fetch_array()) {
    $deviceToken = $row[$i];
    echo $deviceToken;
    $i++;
}

The Issue

You're only obtaining the first value because fetch_array() retrieves a single row from the result set, and you're using the index $i to access elements in that row. However, each subsequent row will have a different index, leading to incorrect results.

Solution

There are several solutions to iterate over the result set:

  • Fetch One by One:

    Use fetch_array() to fetch one row at a time, adjusting the index accordingly:

    while ($row = $output->fetch_array()) {
        echo $row['uid'];
    }
  • Use MySQLI's Iterator:

    MySQLi's query() method can be used as an iterable object, allowing you to iterate over the results as follows:

    foreach ($output as $row) {
        echo $row['uid'];
    }

Note:

You can use either MYSQLI_ASSOC to get associative arrays or MYSQLI_NUM to get indexed arrays as the result set.

Best Practice

Using the object-oriented syntax of MySQLi is recommended, as it streamlines the code. Additionally, it's important to consider the indexes of the rows in your iteration to correctly access the values.

The above is the detailed content of How do I access all results in a MySQLi result set instead of just the first one?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn