2

I want to display all entries present in a table in my MySQL database using for loop (I need for loop for some reason, while loop is not an option). Although I can do it properly in while loop I can't seem to manage to do it with for loop.

Here is my while loop code

while ($row = mysqli_fetch_array($query))  
{
    echo "<p> " . $row['column-name'] . " </p>";
}

How can I convert this to for loop? I mean how to navigate to each rows using for loop's counter variable?

$counter = mysqli_num_rows($result);    

for ($i = $counter; $i > 0; $i--) 
{ 
    echo ????;
}

How should I echo the column name and use the $i as the row reference?

5
  • Tell us why do you need a for loop? Commented Jul 18, 2015 at 10:48
  • because i have to echo it in reverse order Commented Jul 18, 2015 at 10:54
  • 1
    personally I'd keep the while loop and change the SQL to return your data in reverse order using ORDER BY {some-field} DESC Commented Jul 18, 2015 at 10:56
  • you mean by using DESC right ?. i never thought of that. sorry for such a dumb question. fixed it. Commented Jul 18, 2015 at 10:57
  • 1
    exactly, see: Sorting Rows - no worries bud, we all get brain freeze Commented Jul 18, 2015 at 11:07

2 Answers 2

3

You can use a variable outside while loop(thus you get a row reference)
Code shown below

$i=0; // this refer every row..now its 0
while ($row = mysqli_fetch_array($query))  
{
    echo "<p> " . $row['column-name'] . " </p>";
    $i++;  
}

And if you need FOR loop

 
$row = mysqli_fetch_all($query);
    for($i=0;$i<count($row);$i++)
    {

       // thus you get $i as row reference

    }

mysqli_fetch_all returns both numeric and assoc array, so dont forget to select MYSQLI_ASSOC or MYSQLI_NUM
Sign up to request clarification or add additional context in comments.

2 Comments

yes but i need it in for loop. and where did you use the $i ?
@TheJoker..updated answer... if that helps, dont forget to select this as answer :)
-1

If you need the rows to be outputted in the reverse (descending) order, why not just ORDER BY {field} DESC in the query?

Then you can use foreach() to run through all of the results, like this:

$res = $db->query ('SELECT column FROM table ORDER BY column DESC');
$output = '';
foreach ($res->fetch_array () as $line) {
    $output .= "<p>{$line['column']}</p>\n";
}

As you can see, no need for a for loop, a while loop, nor any other fancy tricks. Just echo $output wherever you need it, and the results are sorted just the way you want them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.