【问题标题】:Conditional PHP styling based on variable value基于变量值的条件 PHP 样式
【发布时间】:2015-09-27 20:39:57
【问题描述】:

我有一些 PHP 代码执行并从 SQL 表中选择 10 行。名为result 的一列可以保存赢或输的值。

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "<div class = 'logrow'> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";
    }

我怎么能做一些事情来回显上面每一行的值,但为result 的值丢失的每一行回显不同的语句。例如为背景颜色添加内联样式。

例如,假设我找到了 10 行 - 其中 9 行以 $row["result"]as 获胜,所以它们应该像上面一样回显。但是 1 行的值为 $row["result"] 作为损失,应该应用不同的回声。可能是内联样式,也可能是插入了一个保持这种样式的变量。

我知道这是非常具体的,可能不清楚,所以提前感谢。

【问题讨论】:

  • 只需使用 if...if($row["result"] == 'won')。然后你在 if 和 else 中回显一些不同的东西......
  • 这是否适用于每一行,如果有多个?我总是虽然 while() 必须在这里使用。如果没有,您能否将此作为答案,以便我可以将问题标记为已回答。 TIA
  • @Aba 的回答简单高效 :) 您可以将 css 放入您的实际 css 文件中...
  • 感谢 random :) Aba 的回答绝对很棒

标签: php


【解决方案1】:

基于 $row["result"] (won/loss) 中的值创建一个类并在 echo 中使用它

css:
    .won{background-color::blue}
    .loss{background-color::red}

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "<div class = 'logrow ". $row["result"] ."'> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";
    }

【讨论】:

    【解决方案2】:

    通过更改类名来试试这个。

    <?php 
     $status = $row['result'];
     $classname = 'won';
     if($status == 0){
       $classname = 'fail';
     }
    ?>
    <div class = 'logrow <?php echo $classname ?> '> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";
    

    现在在样式表下为wonfail 定义类。

    <style type="text/css">
    .won{ color: green; }
    .fail{ color: red; }
    </style>
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      相关资源
      最近更新 更多