【问题标题】:PHP using SQL addition of data from multiple colums together into another columnPHP使用SQL将多列中的数据一起添加到另一列中
【发布时间】:2022-01-20 20:26:15
【问题描述】:
<?php

  
    $sql = "SELECT Human, Total_Animals, Snakes, Lizards, Monkeys
    FROM Animals ORDER BY Total Animals DESC";

    $result = $conn->query($sql);
    
    
    if ($result->num_rows > 0) {
        echo "
        <table>
            <tr>
                <th>Human</th>
                <th>Snakes</th>
                <th>Lizards</th>
                <th>Monkeys</th>
                <th>Total Animals</th>
            </tr>";
        // output data of each row

        while($row = $result->fetch_assoc()) {
            echo "<tr>
                <td>".$row["Human"]."</td>
                <td>".$row["Snakes"]."</td>
                <td>".$row["Lizards"]."</td>
                <td>".$row["Monkeys"]."</td>
                <td>".$row["Total_Animals"]."</td>
            </tr>";
        }
        echo "</table>";
    } else {
        echo "0 results";
    }
    $conn->close();
?>

到目前为止,这与我的 .css 文件和我的 html 代码一起工作。我只是想将同一行中的 Snakes、Lizards 和 Monkeys 列相加,然后将值显示在另一列中。

所以在表格格式中它应该是这样的输出

Human  |  Snakes  |  Lizards |  Monkeys  |   Total Animals   |

Fred   |    5     |    3     |     4     |        13         |
Mark   |    3     |    2     |     12    |        17         |

我一辈子都想不出该怎么做。

忽略名称列,假装它有名称。

在 Total Animals 列中,它需要添加 Snakes、Lizards 和 Monkeys 列并在那里显示。

【问题讨论】:

  • 您能否更好地解释一下预期的输出?也许是一张图片?
  • 完成,图片在上面

标签: php html sql


【解决方案1】:

试试这个

SELECT Human, Snakes, Lizards, Monkeys,
(Snakes + Lizards + Monkey) as Total_Animals
 FROM Animals ORDER BY Total_Animals DESC

【讨论】:

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