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

1

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

In my table sql only contains a single integer field id . What I want to do is get the first element that comes from the query sql and treat it just by changing the write color of it.

In my example I have 3 elements registered in the database I can get the 3 but I can not isolate only the first one 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>";
    }
}
    
asked by anonymous 29.04.2017 / 13:45

1 answer

1

You can use an external counter to find out the first pass 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 it all 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;
    
29.04.2017 / 15:04