【问题标题】:In PHP how can I get the count of each instance in a mySQL table column?在 PHP 中,如何获取 mySQL 表列中每个实例的计数?
【发布时间】:2016-03-08 21:34:12
【问题描述】:

为了澄清,我试图让一个表输出以某种方式显示我的 MySQL 数据库表。表格中填满了名字、出生年份和生肖动物。

我想要做的是有一个表格行,上面写着“猫生肖”,然后是“名字”和“出生年份”的标题。在此之下,我想要每个人的姓名和出生年份。我希望对每个生肖动物都这样做。

我遇到的问题是标题显示了黄道带列的每个实例。我知道我的代码是错误的,我只是不知道下一步该怎么做!请帮忙!这是我的代码

$TableName = "zodiacshared";
        $SQLstring = "SELECT * FROM $TableName GROUP BY sign, birthyear";
        $QueryResult = @mysql_query($SQLstring, $DBConnect);
        if (mysql_num_rows($QueryResult) == 0){
            echo "<p> There are no entries in the chinese zodiac gallery! </p>";
        }
        else{
            echo "<table width = '100%' border = '1'>";
            while ($row=mysql_fetch_array($QueryResult)){
                    echo "<th colspan='2'>"; echo $row['sign']; echo " zodiac signs</th>";
                    echo "<tr><th>Name</th><th>Birth Year</th></tr>";
                    echo "<tr>";
                    echo "<td>"; echo $row['name']; echo "</td>";
                    echo "<td>"; echo $row['birthyear']; echo "</td>";
                    echo "</tr>";

            }
            echo "</table>";
            mysql_free_result($QueryResult);
        }

编辑:这可能会有所帮助 我希望的输出是这样的(这是在 Excel 上制作的草稿,但可以理解):

编辑 2:解决方案是:

$current_zodiac= '';
            while ($row=mysql_fetch_array($QueryResult)){
                    if ($row['sign']!=$current_zodiac){
                        echo "<th colspan='2'>"; echo $row['sign']; echo " zodiac signs</th>";
                        echo "<tr><th>Name</th><th>Birth Year</th></tr>";
                    }else{
                        //echo the other rows
                    }
                        echo "<tr>";
                        echo "<td>"; echo $row['name']; echo "</td>";
                        echo "<td>"; echo $row['birthyear']; echo "</td>";
                        echo "</tr>";
                    $current_zodiac = $row['sign']; //assign new zodiac to current zodiac variable

            }

【问题讨论】:

  • 您能否在文本表中显示您希望输出的样子以及 sql 表中的一些示例数据。一半的时间,图片不会对事物产生很多影响。另外,我们不能有效地使用它们

标签: php html mysql html-table row


【解决方案1】:

您可以在 while 循环中使用一个变量来存储当前的星座名称。所以每次生肖名称是唯一的,这意味着在while循环中找到了新的生肖,你可以为它打印新的标题。

例如,流程可能是这样的。

$current_zodiac = '';
while ($row=mysql_fetch_array($QueryResult)){
if ($row['sign']!=$current_zodiac){
 echo "<th colspan='2'>"; echo $row['sign']; echo " zodiac signs</th>";
}else{
//echo the other rows
}
$current_zodiac = $row['sign']; //assign new zodiac to current zodiac variable

}

【讨论】:

  • 非常感谢!这个想法大部分都奏效了,我稍微调整了一下,现在它奏效了。如果没有你的基线,它会花费更长的时间,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多