Search code examples
phploopsmysqliwhile-loopresultset

How do I iterate over the results in a MySQLi result set?


I want to loop through the result set of the following query:

select uid from userbase

I am currently employing the following loop, but I can get only the first value.

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

What might be the problem? Is it fetch_array()?


Solution

  • You need to define a array and store your data into array inside loop . Use MYSQLI_ASSOC no need for incremented value

    $deviceToken=array();
    while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
        $deviceToken[] = $row['uid'];
    }
    print_r($deviceToken);
    for($i=0;$i<=count($deviceToken);$i++){
    echo $deviceToken[$i];
    }