开发者

Display all records for mySQL field and count how many times they appear for specific date

My desired result is to display how many times each video (title) was watched for specific dates, by grabbing all of the titles that appear in the table, and count how many times that title is recorded for specific years / months.

It is working, however, it is not displaying correctly.

Instead of

TITLE A - 2

TITLE B - 6

TITLE C - 4

TITLE D - 0

...

It is displaying like this

TITLE A - 2

- 开发者_高级运维6

- 4

TITLE BTITLECTITLED

my code:

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

    }   

Can anyone offer a solution so that a count will display next to the title? Thanks!


Your code to display the title is outside the loop. If you want the title to be printed next to every value, put it inside the loop printing every value.

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜