2012-04-17 91 views
2

此功能不起作用,我無法找到問題,這是查詢中的某個地方。PHP和MySQL,這個函數有什麼問題?

function get_category_posts($category, $page, $per_page) { 
$start = (int)($page - 1) * $per_page; 
$per_page = (int)$per_page; 

$sql = "SELECT 
    `posts`.`post_id` AS `id`, 
    `posts`.`post_title` AS `title`, 
    `posts`.`post_category` AS `category`, 
    `posts`.`post_body` AS `preview`, 
    `posts`.`post_user` AS `user`, 
    DATE_FORMAT(`posts`.`post_date`, '%Y-%m-%d %H:%i:%s') AS `date`, 
    `comments`.`total_comments`, 
    DATE_FORMAT(`comments`.`last_comment`, '%Y-%m-%d %H:%i:%s') AS `last_comment` 
FROM `posts` 
WHERE `category`='".$category."' 
LEFT JOIN (
    SELECT 
     `post_id`, 
     COUNT(`comment_id`) AS `total_comments`, 
     MAX(`comment_date`) AS `last_comment` 
    FROM `comments` 
    GROUP BY `post_id` 
) AS `comments` 
ON `posts`.`post_id` = `comments`.`post_id` 
ORDER BY `posts`.`post_date` DESC 
LIMIT {$start}, {$per_page}"; 

$posts = mysql_query($sql); 
//die(mysql_error()); 

$rows = array(); 
while (($row = mysql_fetch_assoc($posts)) !== false) { 
    $rows[] = array(
     'id' => $row['id'], 
     'title' => html_entity_decode($row['title']), 
     'category' => html_entity_decode($row['category']), 
     'preview' => html_entity_decode($row['preview']), 
     'user' => html_entity_decode($row['user']), 
     'date' => $row['date'], 
     'total_comments' => ($row['total_comments'] === null) ? 0 : $row['total_comments'], 
     'last_comment' => ($row['last_comment'] === null) ? 'aldrig' : $row['last_comment'] 
     ); 
} 

return $rows; 

} 該功能不需要='".$category."'WHERE類別正常,但是,它返回

您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的使用權語法手冊近「LEFT JOIN(SELECT post_id,COUNT(comment_id)AS total_comments」,在第12行

回答

5

WHERE子句必須出現在表連接後和ORDER BY和限制之前

SELECT <column list> 
FROM <table> 
JOIN <table> USING (<column>) 
WHERE <condition> 
OR <condition> 
AND <condition> 
GROUP BY <column list> 
HAVING <expression> 
+0

如果我把它在連接後,我得到這個前:在「哪裏「未知列‘類別’子句'「 – 2012-04-17 18:58:08

+0

這是因爲類別不在表中 - 它只是一個列別名,嘗試使用'posts.post_category'而不是 – Mikey 2012-04-17 19:24:34

+0

它現在的作品,謝謝。 :) – 2012-04-17 19:38:40

2

聯接已來WHERE條件

$sql = "SELECT 
    `posts`.`post_id` AS `id`, 
    `posts`.`post_title` AS `title`, 
    `posts`.`post_category` AS `category`, 
    `posts`.`post_body` AS `preview`, 
    `posts`.`post_user` AS `user`, 
    DATE_FORMAT(`posts`.`post_date`, '%Y-%m-%d %H:%i:%s') AS `date`, 
    `comments`.`total_comments`, 
    DATE_FORMAT(`comments`.`last_comment`, '%Y-%m-%d %H:%i:%s') AS `last_comment` 
FROM `posts` 
LEFT JOIN (
    SELECT 
     `post_id`, 
     COUNT(`comment_id`) AS `total_comments`, 
     MAX(`comment_date`) AS `last_comment` 
    FROM `comments` 
    GROUP BY `post_id` 
) AS `comments` 
ON `posts`.`post_id` = `comments`.`post_id` 
WHERE `posts`.`category`='".$category."' 
ORDER BY `posts`.`post_date` DESC 
LIMIT {$start}, {$per_page}"; 
+0

我得到這個然後:「'where子句'」中的未知列'category'。 – 2012-04-17 18:58:29

+0

@PeterJonsson,修正了它:) – Starx 2012-04-18 01:07:54