显示mySQL字段的所有记录,并计算它们在特定日期显示的次数

时间:2011-08-09 20:29:07

标签: php mysql while-loop

我想要的结果是显示每个视频(标题)在特定日期被观看的次数,抓住表格中显示的所有标题,并计算特定年份/月份的标题记录次数。

它工作正常,但显示不正确。

而不是

标题A - 2
标题B - 6
标题C - 4
标题D - 0

...

显示如下

标题A - 2
- 6
- 4
TITL BTITLECTITLED

我的代码:

    //get report
    if ($_GET['report'] == "custom") {          //custom date report
        $month = $_GET['month'];
        $year = $_GET['year'];

            $result2 = mysql_query("SELECT DISTINCT title AS displaytitle 
FROM user_history GROUP by title");

        if ($_GET['month'] == "") {

            $result = mysql_query("SELECT title, COUNT(id) FROM user_history
 WHERE year(date) = '$year' GROUP BY title");

        } else {

            $result = mysql_query("SELECT title, COUNT(id) FROM user_history
 WHERE year(date) = '$year' AND month(date) = '$month' GROUP BY title");
        }


            while($row2 = mysql_fetch_array($result2)) {
            $new_title = $row2['displaytitle'];


            echo $row2['displaytitle'];


                while($row = mysql_fetch_array($result)) {
                    echo ' - ' . $row['COUNT(id)'] . '<br />';
                }

    }   

任何人都可以提供解决方案,以便在标题旁边显示计数吗?谢谢!

1 个答案:

答案 0 :(得分:0)

显示标题的代码不在循环中。如果您希望在每个值旁边打印标题,请将其放在循环中打印每个值。

if ($_GET['report'] == "custom") {          //custom date report

    $sql = "
    SELECT
      titles.title,
      COUNT(DISTINCT history.id) AS `count`
    FROM
      user_history titles
    LEFT OUTER JOIN
      user_history history
    ON
      titles.title = history.title
    ";

    if (!empty($_GET['month']) && !empty($_GET['year'])) {
      $sql .= "AND YEAR(history.date) = " . (int)$_GET['year'] . " AND MONTH(history.date) = " . (int)$_GET['month'];
    } else if (!empty($_GET['year'])) {
      $sql .= "AND YEAR(history.date) = " . (int)$_GET['year'];
    }

    $sql .= "
    GROUP BY 
      titles.title
    ORDER BY 
      titles.title
    ";

    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
      echo $row['title'] . ' - ' . $row['count'] . '<br />';
    }

}