2011-11-23 38 views
0

我有以下代碼用於從mysql數據庫中選擇記錄並加載博客文章,我想要做的是統計b_idid的匹配記錄數並仍然顯示博客帖子。PHP/MySQL選擇和計數匹配記錄

$result = $dbc->prepare("SELECT id, title, post, date, time, blog, b_id, name, comment FROM blog ORDER BY id DESC LIMIT $start_blog , $blog_per_page"); 
$result->execute(); 
$result->bind_result($id, $title, $post, $date, $time, $blog, $b_id, $name, $comment); 
while ($row = $result->fetch()) { 
    Code to show the blog posts 
    Show number of comments on the post i.e. Comments (2) 
} 

我必須有一個空白的時刻,因爲我相信它的東西很簡單,但每當我使用的代碼

count (b_id) WHERE b_id = id 

的博客文章沒有顯示(即其計數的比賽和不發送博客文章的數據。

希望這是有道理

問候 吉姆

回答

1

將b_id與其數據外包給另一個表可能更有意義,但這取決於您嘗試實現的目標。

反正正確地回答你的問題,你既可以做2個獨立的查詢(一個與計數,其他所有的數據),或者只是讓PHP處理:

$count = 0; 
if($b_id == $id) { $count++; } 
0

好了,經過多次試驗和錯誤我設法做到這一點與左連接。如果任何人發現它的使用或興趣,這裏是代碼。

$result = $dbc->prepare("SELECT blog.id, blog.title, blog.post, blog.date, blog.time, count(blog_comment.b_id) CommCount FROM blog LEFT JOIN blog_comment ON blog.id = blog_comment.b_id GROUP by blog.id ORDER BY id DESC LIMIT $start_blog , $blog_per_page"); 
$result->execute(); 
$result->bind_result($id, $title, $post, $date, $time, $b_id); 
while ($row = $result->fetch()) { 
    //Code to show blog posts, using $b_id to display the number of comments 
} 

非常感謝您的幫助和投入,它們都添加到找到我渴望的解決方案!

Jim

相關問題