2016-10-26 75 views
0

如果time2大於時間1,我希望背景顏色更改爲紅色。 我是一個完全noob在這和我現在試了幾天,但沒有得到它的工作。 在CSS我有.bgred {background: red;}用PHP中的if語句更改backgroundcolor

<?php 
$sql = ("SELECT name, time1, time2 FROM myTable WHERE dates LIKE '".$_POST['dat']."' "); 
$result = mysqli_query($conn, $sql);   

if (mysqli_num_rows($result) > 0) {  

    echo "<table action='' method='POST'><tr> 
    <th>Name</th> 
    <th>Time1</th> 
    <th>Time2</th></tr>"; 

    // output data of each row 
    while($row = mysqli_fetch_assoc($result)) { 

     $var1 = $row["time1"]; 
     $var2 = $row["time2"]; 
     if($var2 < $var1) { 
      $bgred = 'class="bgred"'; 
     } else { 
      $bgred = ''; 
     } 

     echo "<tr><td>".$row["name"]."</td> 
     <td>".$row["time1"]."</td> 
     <td class="$bgred">".$row["time2"]."</td></tr>"; 
     } 
    } 

    echo "</table>"; 

mysqli_close($conn); 
?> 
+0

http://stackoverflow.com/a/39444025/3558278 – Deep

回答

0
$bgred = null; 
$rows = null; 

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


    $var1 = $row["time1"]; 
    $var2 = $row["time2"]; 
    if($var2 < $var1) { 
     $bgred = 'class="bgred"';  
    } else { 
     $bgred = ''; 
    } 

    $rows .= '<tr> 
        <td>' . $row["name"] . '</td> 
        <td>' . $row["time1"] . '</td> 
        <td>' . $row["time2"] . '</td> 
      </tr>'; 
} 

echo '<table action="" method="POST"> 
     <tr> 
      <th>Name</th> 
      <th>Time1</th> 
      <th class="' . $bgred . '">Time2</th> 
     </tr> 
     ' . $rows . ' 
    </table>'; 

你有一個理由使用雙引號?

1

你是不是呼應了$ bgred任何地方。

<?php 
$sql = ("SELECT name, time1, time2 FROM myTable WHERE dates LIKE '".$_POST['dat']."' "); 
$result = mysqli_query($conn, $sql); 

if (mysqli_num_rows($result) > 0) { 

echo "<table action='' method='POST'><tr> 
<th>Name</th> 
<th>Time1</th> 
<th>Time2</th></tr>"; 

// output data of each row 
while($row = mysqli_fetch_assoc($result)) {  


    $var1 = $row["time1"]; 
    $var2 = $row["time2"]; 

//edited here 
    if(strtotime($var2) < strtotime($var1)) { 
     $bgred = 'bgred'; 
//done with edit  
    } else { 
     $bgred = ''; 
    } 

    echo "<tr><td class='$bgred'>".$row["name"]."</td> 
    <td class='$bgred'>".$row["time1"]."</td> 
    <td class='$bgred'>".$row["time2"]."</td></tr>";  
    }  
}  

echo "</table>"; 
mysqli_close($conn); ?> 
+0

我編輯了我的文章。我有「。$ row [」time2「]。」「; 但它仍然無法正常工作 –

+0

如果您查看源代碼,那麼正確的代碼有class = bgred?也在您的css中嘗試background-color:red; – Chris

+0

還有什麼類型的字段是數據庫中的時間?timestamp,日期等?編輯答案轉換爲unix時間之前比較 – Chris