如何在表格中只显示一次变量。
<?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
---------------
答案 0 :(得分:2)
您可以直接在SQL中执行此操作。警告:我实际上没有测试过这个。
SELECT week, count(week) FROM babydata GROUP BY week;
这将直接返回
之类的结果--------------
week4 | 2
week5 | 3
--------------
只需将week
替换为周字段的实际名称,并调整PHP以处理新的结果结构。这些方面的东西:
$sql= mysql_query("SELECT * FROM babydata");
while($row = mysql_fetch_array($sql))
{
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
答案 1 :(得分: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>";
}
这假设您的表week
中的列babydata
仅包含一个数字。这只输出几周,至少有一个元组。