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
Release: 2024-11-16 19:02:03
Original
731 people have browsed it

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 
Copy after login

Your loop:

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

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'];
    }
    Copy after login
  • 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'];
    }
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template