简体   繁体   English

根据php中数据库的值突出显示不同颜色的表行

[英]Highlight table row in different colors based on values from database in php

The code below has dynamic drop down list, that users chooses preferred brand and model, accordingly the table is generated in the webpage which results of brand, model and year . 下面的代码具有动态下拉列表,用户可以选择喜欢的品牌和型号,因此在网页中将生成品牌,型号和年份的结果表。 Now the code needs to group all the same year with different models and highlight them with set of different colors for each year accordingly. 现在,代码需要将同一年的所有年份用不同的模型进行分组,并相应地用每年不同的颜色突出显示它们。 An expected results is attached as image. 预期的结果作为图像附上。

// (___ & !!!) or (ALL & ___) or (ALL & ALL)
if ((!isset($_POST['model']) || ($_POST['brand'] == 'ALL' && empty($_POST['model']))) || ($_POST['brand'] == 'ALL' && $_POST['sip'] == 'ALL')) {
    $query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` ORDER BY brand,model,year';
}
// (... & ...) or (... & ALL)
else if (!empty($_POST['brand']) && (empty($_POST['model']) || ($_POST['model'] == 'ALL'))) {
    $query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE brand="'.$_POST['brand'].'" ORDER BY brand,model,year';
}
// (ALL & ...) or (ALL & notALL)
else if ($_POST['brand'] == 'ALL' && (!empty($_POST['model']) && $_POST['model'] != 'ALL')) {
    $query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE model="'.$_POST['model'].'" ORDER BY brand,model,year';
}
else {
    $query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE brand="'.$_POST['brand'].'" AND model="'.$_POST['model'].'" ORDER BY brand,model,year';
}
//echo $_POST['brand'].'<br />'.$_POST['model'];

echo '<table border=1><tr><th>BRAND</th><th>MODEL</th><th>YEAR</th></tr>';
$result1 = mysqli_query($con, $query1);


    while($row1 = mysqli_fetch_array($result1)){
    //echo'<tr><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';

        $query2= 'SELECT DISTINCT brand,model,year, count(*) `number` FROM `carlist` WHERE brand="'.$_POST['brand'].'" GROUP BY `year` HAVING count(*) > 1';
        $result2= mysqli_query($con, $query2);
        $count=0;


        while($row2 = mysqli_fetch_array($result2)){

            if ( $row2['year'] == $row1['year']) {
            $count=1;
            }

            //$intersect = array_intersect($row1,$row2);
            //echo $intersect[1];


        }

        $bgcolor = "#FF8C00"; 
        if($count==1){
            echo '<tr style="background-color: tomato;" ><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';

        }else {

            echo'<tr><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
        } 

    }


echo '</table>';

Method 1: 方法1:

This won't need to do a nested loop. 这不需要做嵌套循环。 This first method will only work if your row is arranged by year. 仅当您的行按年份排列时,第一种方法才有效。

/* DEFINE THIS VARIABLE FIRST BEFORE YOUR LOOP */
$yearstorage = ""; /* STORAGE FOR YOUR YEAR AND COMPARISON LATER */
$randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE RANDOM COLOR */

/* START OF YOUR LOOP */
while($row1 = mysqli_fetch_array($result1)){

  $res = mysqli_query($con,"SELECT * FROM carlist WHERE year=".$row1['year']."");
  if(mysqli_num_rows($res) > 1){ /* IF YEAR HAS ONLY ONE ROW */
    $randomcolor = "#ffffff";
  }

  if(empty($yearstorage)){ /* START OF FIRST ROW */
    ?>
      <tr style="background-color: <?php echo $randomcolor ?>;">
    <?php
    $storecolor = $randomcolor;
  }

  else if($yearstorage == $row1["year"]){ /* IF LAST YEAR ROW IS THE SAME AS THE CURRENT YEAR ROW */
    ?>
      <tr style="background-color: <?php echo $storecolor ?>;">
    <?php
  } 

  else { /* IF THE LAST YEAR ROW IS NOT THE SAME WITH THE CURRENT YEAR ROW */
    $randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE NEW RANDOM COLOR */
    ?>
      <tr style="background-color: <?php echo $randomcolor ?>;">
    <?php
    $storecolor = $randomcolor;
  }

  $yearstorage = $row1["year"]; /* STORE THE CURRENT YEAR FOR COMPARISON ON THE NEXT LOOP */

    ?>
        <td><?php echo $row1['brand']; ?></td>
        <td><?php echo $row1['model']; ?></td>
        <td><?php echo $row1['year']; ?></td>
      </tr>
    <?php

} /* END OF WHILE LOOP */

Method 2: 方法2:

This second method will work even if your row is not arrange in year. 即使您的行未按年份排列,第二种方法也将起作用。 Even if arranged by different column name which I would refer more to you. 即使按不同的列名进行排列,我也会向您详细介绍。

You have to create a loop to get all the year distinctly, and store the color and year in an array, and compare and get them on your main loop. 您必须创建一个循环以清楚地获取所有年份,然后将颜色和年份存储在数组中,然后在主循环中进行比较并获取它们。

No need to do a nested loop also. 也无需执行嵌套循环。 But two separated loop. 但是两个分开的循环。

As you will notice, this code is also shorter than the first method. 您会注意到,此代码也比第一种方法短。

If a year contains one row only, it will have a white background. 如果一年仅包含一行,则背景为白色。

$counter = 0; /* DETERMINER OF THE COLOR TO BE USED LATER */
$res = mysqli_query($con,"SELECT DISTINCT year FROM carlist");
while($row = mysqli_fetch_array($res)){
  $randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE NEW RANDOM COLOR */
  /* STORE THE COLOR AND YEAR IN AN ARRAY */

  $res2 = mysqli_query($con,"SELECT * FROM carlist WHERE year = ".$row['year']."");
  if(mysqli_num_rows($res2) > 1){ /* IF YEAR IS USED MORE THAN ONCE */
    $colorstorage[$counter] = $randomcolor;
  }
  else { /* ELSE, IT WILL HAVE A WHITE BACKGROUND */
    $colorstorage[$counter] = "#ffffff";
  }
  $yearstorage[$counter] = $row['year'];
  $counter = $counter + 1; /* INCREMENT COUNTER */
} /* END OF LOOP THAT STORES THE COLOR AND YEAR IN AN ARRAY */

/* START OF YOUR MAIN LOOP */
while($row1 = mysqli_fetch_array($result1)){

  $key = array_search($row1["year"],$yearstorage);
  ?>
    <tr style="background-color: <?php echo $colorstorage[$key]; ?>;">
      <td><?php echo $row1['brand']; ?></td>
      <td><?php echo $row1['model']; ?></td>
      <td><?php echo $row1['year']; ?></td>
    </tr>
  <?php

} /* END OF YOUR MAIN LOOP */

Create function what generates random color 创建产生随机颜色的函数

function getColor($year){
  return '#'.substr(md5($year), 0, 6);
}

In your while loop 在您的while循环中

// Get color for current year
// Same years will be colored with same color
$bgColor = getColor($row1['year']);

// Print table row
echo '<tr style="background-color: '.$bgColor.';"><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';

So your while loop will be 所以你的while循环将是

while($row1 = mysqli_fetch_array($result1)){

    // Delete extra while and if condition

    $bgColor = getColor($row1['year']);
    echo '<tr style="background-color: '.$bgColor.';"><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
}

NOTE: Your queries are vulnerable to SQL injection. 注意:您的查询容易受到SQL注入的攻击。 Please see this answer on how to prevent it. 请参阅有关如何预防的答案

NOTE 2: Since your background colors are generated automatically, it may happen that text is not easily readable. 注意2:由于背景颜色是自动生成的,因此可能会导致文本不容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM