我有一个数据库和表,它获取OID结果并将它们插入到表中。这个表中有多种类型的值,我需要最终的表能够区分它们。我使用group by对结果进行排序,并通过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(),因为只要风扇速度在test列中,该值就会在其表方框的末尾添加一个%,并且每当温度出现在test列中时,我需要一个F出现在值方框中。数据目前在我的数据库中存储为一个简单的整数。
--------------------
|Fan Speed | 55 % |
----------------------
|Temperature| 70 F |
--------------------发布于 2013-04-04 07:51:30
只需去掉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查询中使用Ceses语句来填充如下所示的新字段:
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
}发布于 2013-04-04 07:54:05
如果我理解不正确,请让我知道!
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>";
}
}https://stackoverflow.com/questions/15800158
复制相似问题