For each loop add 1 in PHP

时间:2018-01-23 19:34:44

标签: php mysql

I have been trying to return a list of results from MySQL using PHP.

The basic query is simple and the output is multiple columns. I want to add a number so the array looks like this:

  1. Club 1
  2. Club 2

I have tried the below but it keeps breaking the script:

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        for($i=1; $i++){
            $club = $row['club_name'];
            echo '<p>' . $i . $club . '</p>';
        }           
    }
} 

I have then tried placing the for statement outside the while and inside it, changed it to foreach and used the format ($i=1; $i<100; $i++){} and it still doesn't work.

Sorry if this is an obvious one I've tried numerous different ways and it just isn't working for me.

1 个答案:

答案 0 :(得分:5)

Try creating a counter variable ($i) and incrementing it on every iteration of the while loop ($i++), like this:

if (mysqli_num_rows($result) > 0) {
    $i = 1;
    while($row = mysqli_fetch_assoc($result)) {
        $club = $row['club_name'];
        echo '<p>' . $i . $club . '</p>';
        $i++;
    }
}

Then, to change the format to match 1. Club Name, change

echo '<p>' . $i . $club . '</p>';

to

echo "<p>$i. $club</p>";

But, I'd personally recommend to use an <ol> instead and skip setting the counter altogether like this:

if (mysqli_num_rows($result) > 0) {
    echo "<ol>";
    while($row = mysqli_fetch_assoc($result)) {
        $club = $row['club_name'];
        echo "<li>$club</li>";
    }
    echo "</ol>";
}
相关问题