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

时间:2013-04-03 23:42:28

标签: 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(),因为每当风扇速度在测试列中时,该值都会添加一个%它是表格的正方形,每当测试栏中出现温度时,我需要一个F出现在数值方块中。数据当前存储为数据库中的简单整数。

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

2 个答案:

答案 0 :(得分:1)

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

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
    }

答案 1 :(得分:0)

如果我不明白,请告诉我!

while($row = mysql_fetch_array($result))
    {
if( $row['value']==70)
{
    echo"<tr>";

    echo"<td>". $row['device']. "</td><td>F</td>";

    echo"</tr>";
    }else
{
 echo"<tr>";

    echo"<td>". $row['device']. "</td><td>" % . "</td> 

    echo"</tr>";
}
}
相关问题