php - 如何将 If then 语句放入 php 中的 mysql_fetch_array() 语句中

标签 php mysql arrays html-table

我有一个数据库和表,可以获取 OID 结果并将其插入到表中。该表内部有多种类型的值,我需要最终的表才能区分这些值。我对结果进行了分组排序,并通过 mysql_fetch_array() 将结果过滤到表中。

这是我的代码。

$result = mysql_query("SELECT MAX(t1)AS t1, device, test, value FROM ACRC WHERE        test='Fan Speed' GROUP BY device, test ORDER BY device ASC, test ASC LIMIT 4");

echo "<table border='3' cellpadding='3'>
    <tr>
    <th>Timestamp</th>
    <th>Unit</th>
    <th>Test</th>
    <th>Result</th>
    </tr>
    <tbody>";

while($row = mysql_fetch_array($result))
    {
    echo"<tr>";
    echo"<td>". $row['t1']. "</td>";
    echo"<td>". $row['device']. "</td>";
    echo"<td>". $row['test']. "</td>";
    echo"<td>". $row['value']." %</td>";
    echo"</tr>";
    }


$result = mysql_query("SELECT MAX(t1)AS t1, device, test, value FROM ACRC WHERE test<>'Fan Speed' GROUP BY device, test ORDER BY  test ASC, device ASC LIMIT 8");


while($row = mysql_fetch_array($result))
    {
    echo"<tr>";
    echo"<td>". $row['t1']. "</td>";
    echo"<td>". $row['device']. "</td>";
    echo"<td>". $row['test']. "</td>";
    echo"<td>". $row['value']." F</td>";
    echo"</tr>";
    }


echo"</table>";

此设置当前有效,但我想使用 if/then/else 语句将其压缩为一个 mysql_fetch_array() ,因为只要风扇速度位于测试列中,该值就有一个 %添加到其表格方 block 的末尾,每当测试列中出现温度时,我需要在值方 block 中出现一个 F。数据当前作为简单整数存储在我的数据库中。

 --------------------
|Fan Speed  | 55   % |
----------------------
|Temperature| 70   F |
 --------------------

最佳答案

只需删除 WHERE 条件,以便所有结果都出现在一个查询中。然后,正如您在问题标题中提到的那样,使用 if() 条件回显结果以确定是否输出 %F 或任何下一个顶部值。

while($row = mysql_fetch_array($result))
    {
?>
<tr>
    <td><?php echo $row['t1']; ?></td>
    <td><?php echo $row['device']; ?></td>
    <td><?php echo $row['test']; ?></td>
    <td><?php echo $row['value']; ?> <?php echo('$row['test'] === 'Fan Speed' ? '%' : 'F'); ?></td>
</tr>
<?php
    }

或者,如果您想变得更花哨并保持代码整洁,您甚至可以在 SQL 查询中使用 case 语句来填充新字段,如下所示:

SELECT
  MAX(t1)AS t1,
  device,
  test,
  value,
  (CASE test WHEN 'Fan Speed' THEN '%' ELSE 'F') AS symbol
FROM ACRC
...

代码可以是:

while($row = mysql_fetch_array($result))
    {
?>
<tr>
    <td><?php echo $row['t1']; ?></td>
    <td><?php echo $row['device']; ?></td>
    <td><?php echo $row['test']; ?></td>
    <td><?php echo $row['value'] . ' ' . $row['symbol']; ?></td>
</tr>
<?php
    }

关于php - 如何将 If then 语句放入 php 中的 mysql_fetch_array() 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15800158/

相关文章:

php - 多维数组

php - 无法对齐 html 表单中的元素

MySQL - 返回值=3的行号

Mysql - Mysql2::错误:不正确的字符串值:

objective-c - Swift: "Mapper is not a type",在 swift 和 Objective C 中为数组使用自定义映射类

php - 使用 PHP 获取具有相同名称的 2 个 HTML 输入标签的值

PHP - 无法执行 C++ 二进制文件?

mysql - 未知列,即使该列存在

c++ - 将 char 数组分配给另一个 char 数组

java - 2D 数组方法和演示