How to know the result number inside a loop with mysqli_fetch_array?

Asked

Viewed 95 times

1

How to know the result number within a loop with mysqli_fetch_array to have a condition that separates the first from the rest?

On my table sql only contains a single entire field id. What I want to do is take the first element that comes from the query sql and treat the same just by changing the writing color of the same.

In my example I have 3 elements registered in the database I can take the 3 but I can not isolate only the first to make the color change

as I’m trying to do to print the elements

while($aux = mysqli_fetch_array($sql)){
    $id = $aux['id'];

    if($id[0]){
        echo "<span style=\"color:red\">$id</span>";
    }else{
        echo "<span>$id</span>";
    }
}

1 answer

1


You can use an external counter to know which is the first passage of the loop:

$i = 0;
while($aux = mysqli_fetch_array($sql)){
    $id = $aux['id'];
    if($i == 0){
        echo "<span style=\"color:red\">$id</span>";
    }else{
        echo "<span>$id</span>";
    }
    $i++;
}

Another alternative is to create a string, and send everything at the end:

$html = '';
while($aux = mysqli_fetch_array($sql)){
    $id = $aux['id'];
    if(strlen($html) == 0){
        $html.="<span style=\"color:red\">$id</span>";
    } else {
        $html.="<span>$id</span>";
    }
}
echo $html;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.