I have three tables: posts, author and comments. I want to perform a join cross three tables to retrieve Post details, author and the comments to that post id.
My query is as follow:
$q = " SELECT p.page_name, p.content,";
$q .= " DATE_FORMAT(p.post_on, '%b %d, %y') AS date, ";
$q .= " CONCAT_WS(' ', u.first_name, u.last_name) AS name, u.user_id, ";
$q .= " COUNT(c.comment_id) AS count";
$q .= " FROM pages AS p ";
$q .= " INNER JOIN users AS u ";
$q .= " USING (user_id) ";
$q .= " INNER JOIN comments as c ";
$q .= " USING (page_id) ";
$q .= " WHERE p.page_id = {$pid} ";
$q .= " ORDER BY date ASC";
This query runs well and good if the $pid is valid or exists. But if the Post ID does not exists, it will be a blank page. Because the query still returns one row contains NULL value and number of comment of 0 due to the aggregation function count(). This row renders my my else clause useless.
if(mysqli_num_rows($r) > 0) {
// code to print post
} else {
echo "post not found";
}
I know there is must be a good way to overcome this, but I seem cannot get it to work. Any help will be very much appreciated.
I am sorry if the question seem ambiguos.