对于我的新闻发表评论系统,我无法从2个表(tbl_news和tbl_comments)获取查询结果。在我使用mysqli制作的另一个程序中,内部联接工作但现在这次使用PDO我无法使其工作。
这是我的代码:
$newsQuery = $db->prepare("SELECT *
FROM tbl_news
INNER JOIN tbl_comments ON tbl_news.news_id = tbl_comments.news_id
ORDER BY news_id DESC
LIMIT 5");
$newsQuery -> execute();
while($newsFetch = $newsQuery->fetch(PDO::FETCH_OBJ)) {
echo "<div class='news-post'><h3 class='post-title'>" . $newsFetch->title . "</h3>
<p style='float:left'>By: <span class='post-author'>" . $newsFetch->author . "</span></p>
<p style='float:right'>Date: <span class='post-date' style='font-style:italic;'>" . $newsFetch->date . "</span></p>
<br><p>" . $newsFetch->text . "</p></div>";
if(isset($_SESSION['user']) && ($newsFetch->comments == '1')) {
echo "Comments(";
echo "<div id='commentClick'>Click <a href='#' id='openForm'>here</a> to post a comment</div>";
echo "<form class='navbar-form' id='commentForm'><input style='margin-right:5px' type='text' size='80%' name='commentText' placeholder='Type your comment here'><input type='submit' class='btn btn-primary btn-xs' value='Send'></form>";
}elseif(!isset($_SESSION['user']) && ($newsFetch->comments == '1')) {
echo "Click here to view comments. If you want to post comments please login first";
}else{
echo "Comments are disabled for this news item";
}
}
在数据库中,我有以下值: 在tbl_news中有一个news_id,在tbl_comments中有comment_id,news_id和user_id。
提前致谢!
答案 0 :(得分:0)
您需要为数据库表名使用别名,例如:
SELECT n.*, c.* FROM tbl_news n
INNER JOIN tbl_comments c ON n.news_id = c.news_id
ORDER BY n.news_id DESC LIMIT 5
答案 1 :(得分:0)
您的内部联接查询应该是这样的
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
我的意思是你需要指定tablename.columnname而不是使用all(*)
修改强>
1052 Column 'news_id' in order clause is ambiguous'
当您在一个语句中连接两个或多个表时会发生此错误,并且这些表中的列之间具有相同的名称,并且在引用语句中的列时未使用表名为列名添加前缀。