简体   繁体   中英

php while loop - if statement for each row of mysql query

I'm working on a program that queries a mysql db and displays the results in an html table. I want to have conditional formatting based upon one of the field values. If the query returns the word "In", I want the table cell background color to be green; If the word "Out" appears, red. I've gotten to the point where it is coloring the cells, but it appears to be using the color of the first row's word for the first and all subsequent rows. Say, for instance, that the first row's word is "In", then that cell will be green, and all cells below it, even if other cells have the word "Out". Here is the relevant part of the code:

...

while($row = mysqli_fetch_array($result)) {     

            echo "<tr>";
            echo "<td>" . $row['Employee'] . "</td>";
            $color_test = $row['Status'];
            if ($color_test = "In") {
                echo "<td bgcolor=#00FF00>" . $row['Status'] . "</td>";
                }
            elseif ($color_test = "Out") {
                echo "<td bgcolor=#FF0000>" . $row['Status'] . "</td>";
                }
            else {}

            echo "<td>" . $row['Return'] . "</td>";
...

The only thing I can think of is that the if statement is not being applied to all rows. I'm not sure how this would be done. I've not programmed much in php.

if($color_test = "In")

should be

if($color_test == "In")

Now, you are assigning the "In" string to the variable $color_test , but you should check the equality with the == operator.

如果要在if语句中进行比较,则需要使用==

while block should be like this .

   while($row = mysqli_fetch_array($result)) {     

        echo "<tr>";
        echo "<td>" . $row['Employee'] . "</td>";
        $color_test = $row['Status'];
        if ($color_test == "In") {
            echo "<td bgcolor=#00FF00>" . $row['Status'] . "</td>";
            }
        elseif ($color_test == "Out") {
            echo "<td bgcolor=#FF0000>" . $row['Status'] . "</td>";
            }
        else {
              echo "<td>" . $row['Return'] . "</td>";
          }
     }

a few corrections :

You're using mysqli_fetch_array() when you're trying to get a row - use mysqli_fetch_assoc() instead.

while($row = mysqli_fetch_assoc($result)) {  

Inside the if predicates, you are using only one =, which uses for assigning values, use == instead.

if( $color_test == "In" )
if( $color_test == "Out" )

And just a little comment, you already assigned a variable called $color_test, it would be better if you use this variable at the printing instead using $row[] when printing.

That's all I think

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