开发者

MySQL Sort by Month in PHP script

开发者 https://www.devze.com 2023-03-04 06:46 出处:网络
Trying to get my results sorted by month and displayed in a table. Where am I going wrong? Query: mysql_query(\"SELECT COUNT(*), DATE_FORMAT(DATE(`dPostDateTime`), \'%W, %b, %e\') AS `day`, DATE(`dP

Trying to get my results sorted by month and displayed in a table. Where am I going wrong?

Query:

mysql_query("SELECT COUNT(*), DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDat开发者_Go百科eTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`");

PHP Code:

while($row = mysql_fetch_assoc($monthlyQ))
{
$printedRecords1++;
echo "<tr class='forum'>";
echo "<td class='forum'>" . $row['month'] . "</td>";
echo "<td class='forum'>" . $row['COUNT(*)'] . "</td>";
echo "</tr>";
}
for ($i = $printedRecords1; $i < $Print; $i++) {
echo "<tr class='forum'>"; 
echo "<td class='forum'>&nbsp;</td>";
echo "<td class='forum'>&nbsp;</td>";
echo "</tr>";
}
echo "</table></td><td>";


I assume when you say you're trying to sort by month, you just mean you're trying to figure out how many rows are in each month, since that looks what what your code is doing.

If you actually have a 'month' field in your table, then your SQL is fine, except that you never actually select that field, so $row['month'] shouldn't have a value with that SQL.
So you need to select it like below:

mysql_query("SELECT COUNT(*), `month`, DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDateTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`");

If you don't have a 'month' field (and just have the date field, which would mean your query as given shouldn't be working) you need to be creating that in a similar way as your 'day'.

mysql_query("SELECT COUNT(*), MONTH(`dPostDateTime`) AS `month`, DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDateTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`");

Then, if you want your results to be ordered by the month as well, so the table goes in a cronological order, you'd want to add ORDER BY month in there as well, assuming it exists (as in example 1) or you're creating it (as in example 2).


If you want them sorted by month, then you need to add

ORDER BY `month`

to your SQL

0

精彩评论

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