回显变量一次


Echo variable once

如何在表中只显示一次变量。

<?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,它只包含一个数字。这只输出至少有一个元组的周。

您可以直接在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>";
}