dsgk0386 2012-03-29 22:22
浏览 41
已采纳

回声变量一次

How can i display variable only once in the table.

<?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>";
        }
    }
}
?>

this code display like this:

--------------
week4 |  1
-------------
week4 |  1
-------------

But i want to display weeknumber only once and count($row[$menucompare]) will be counted 2 in week 4 . not 1 and 1 .

Like this:

--------------
week4 | 2
---------------
  • 写回答

2条回答 默认 最新

  • duanliang5051 2012-03-29 22:42
    关注

    Seems like you want to output the amount of tuples in babydata for a certain week. You can just filter out any tuples which dont belohnt to the $weeknumber in your query.

    // 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>";
    

    No need for loops.

    To output all weeks and their respective amount of data:

    // 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>";
    }
    

    This assumes that you have a column week in your table babydata that contains just a number. This outputs only weeks, that have at least one tuple.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条