如何在表格中只显示一次变量。
<?php
$sql = mysql_query("SELECT * FROM babydata");
while ($row = mysql_fetch_array($sql)) {
for ($i = 1; $i <= 72; $i++) {
if ($i == $weeknumber) {
echo "<tr><td width='40'>Week $i</td>";
echo "<td width='500' >" . count($row[$menucompare]) . "</td></tr>";
}
}
}
?>
这段代码显示如下:
--------------
week4 | 1
-------------
week4 | 1
-------------
但我只想显示周数一次,count($row[$menucompare])
将在第 4 周计数为 2。不是 1 和 1 。
像这样:
--------------
week4 | 2
---------------
您似乎想输出某周 babydata 中元组的数量。您可以过滤掉查询中不属于 $weeknumber
的所有元组。
// TODO: Assert, that $weeknumber is an integer, to not be prune to SQL injection.
$weeknumber = (int)(($currentdate - $birthday) / (7 * 24 * 60 * 60)) + 1;
// Select the amount of tuples in babydata for the desired $weeknumber.
$result = mysql_query("SELECT count(*) FROM babydata ".
"WHERE week = $weeknumber");
// There is only one tuple with one column that contains the amount as number.
$row = mysql_fetch_row($result);
// Output the week and the amount of data.
echo "<tr><td width='40'>Week $weeknumber</td>" ;
echo "<td width='500' >".$row[0]."</td></tr>";
不需要循环。
要输出所有星期及其各自的数据量:
// Select the amount of tuples in babydata for all weeks.
$result = mysql_query("SELECT week, count(*) FROM babydata ".
"GROUP BY week");
// For all weeks:
while ($row = mysql_fetch_row($result))
{
// Output the week and the amount of data.
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
假设您的表 babydata
中有一列 week
,它只包含一个数字。这只输出至少有一个元组的星期。
我是一名优秀的程序员,十分优秀!