Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP and MySQL, what's wrong with this function?
    primarykey
    data
    text
    <p>This function doesn't work and I can't find the problem, which is somewhere inside the query.</p> <pre><code>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' =&gt; $row['id'], 'title' =&gt; html_entity_decode($row['title']), 'category' =&gt; html_entity_decode($row['category']), 'preview' =&gt; html_entity_decode($row['preview']), 'user' =&gt; html_entity_decode($row['user']), 'date' =&gt; $row['date'], 'total_comments' =&gt; ($row['total_comments'] === null) ? 0 : $row['total_comments'], 'last_comment' =&gt; ($row['last_comment'] === null) ? 'aldrig' : $row['last_comment'] ); } return $rows; </code></pre> <p>} The function works fine without the <code>WHERE</code>category<code>='".$category."'</code>, however, with it it returns </p> <blockquote> <p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN ( SELECT <code>post_id</code>, COUNT(<code>comment_id</code>) AS <code>total_comments</code>, ' at line 12</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload