简体   繁体   中英

Mysql Query wont echo all results! PHP

My code goes like this,

$sql = "SELECT Month(time) as Month, Year(time) as Year,
title, COUNT(*) AS total FROM posts GROUP BY Year, Month ORDER BY time DESC";

$stmt = $conn->query($sql);

if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_array()){
  echo "<div class=title>" . $row["title"]. "</div>";
}
}

it is supposed to output 4 titles,

Bellavisa
Mist Neting
Turkey is cool!
Cock of the Rock

but it only outputs

Bellavisa

Turkey is cool!

Cock of the Rock

Note that bellavisa and mist neting are in the same year and month, (setting up an archive list)

EDIT

Here is some of the table data

title "bellavisa" content "yadadada" time "timestamp ..." Author "author"   

title "mist nesting" content "yadadada" time "timestamp ..." Author "author"

Well, title is per post, so to get all the titles you should use no GROUP BY , while COUNT(*) is per month, so to get counts you need to GROUP BY the way you do, so in a simple SELECT you can either select one or another, but not both.

To select both, you need to use a subquery, something along the lines of

$sql = "SELECT Month(time) as Month, Year(time) as Year, title, (SELECT COUNT(*) FROM posts WHERE Month(time) = Month AND Year(time) = Year) AS total FROM posts ORDER BY time DESC;";

Effectively, the query selects all the posts, and for each post computes a count. It is not the most efficient way to do that, you can rewrite it using a join, if every post has a unique ID. But for a table with reasonable size this query will work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM