简体   繁体   中英

using php for loop for mysqli_fetch_array

I want to use for loop instead of using the conventional while loop

Like this one (psuedo code):

$list = mysqli_fetch_array($result);

for($x = 0; $x < sizeof($list); $x++){
    echo $x;
}

Is this possible?

There's no reason why you can't use a while loop. That being said, when you now use sizeof($list) , you will get the number of columns selected from the query (this $list variable has as many elements as columns was selected). You will therefor attempt to loop (and ouput the count of) the number of columns you fetched.

Instead, you might want to do something like this below - fetch the number of rows based on mysqli_num_rows() , which is exactly that - the number of rows returned by the query.

for ($x = 0; $x <= mysqli_num_rows($result); $x++) {
    $row = mysqli_fetch_array($result);
    var_dump($row);
}

Although, the standard way - and in my opinion the best way - of doing it is via while .

while ($row = mysqli_fetch_array($result)) {
    var_dump($row);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM