0
所以這段代碼只有在我調用的表匹配請求時才起作用,但是我仍然想要顯示主表的所有值,即新聞n表。什麼是解決這個在PHP中選擇多個表MYSQL
在這裏,我剛剛完成我的查詢
$query="SELECT * FROM news n,category c, comments a, appusers u, admins w WHERE n.cat_id=c.category_id AND w.userId=n.post_author AND a.post_id=n.id AND u.user_id=a.userID ORDER BY a.commentid DESC, n.id DESC";
$result = mysql_query($query);
$json_response = array();
while($row=mysql_fetch_array($result)) {
if (!isset($json_response[ $row['id'] ])) {
$json_response[ $row['id'] ] = [
'id' => $row['id'],
'title' => $row['title'],
'catId' => $row['cat_id'],
'catName' => $row['category_name'],
'catImage' => $row['category_image'],
'postDate' => $row['post_date'],
'postImage' => $row['post_image'],
'post' => $row['post'],
'commentCount' => $row['comment_count'],
'videoUrl' => $row['video_url'],
'tags' => $row['tags'],
'author' => $row['tags'],
'comments' => [],
];
}
$json_response[ $row['id']]['comments'][] = [
'id' => $row['commentid'],
'comment' => $row['comment'],
'name' => $row['user_name'],
'userId' => $row['userID']
];
}
$data = [];
foreach ($json_response as $element) {
$data[] = $element;
}
echo json_encode($data, JSON_PRETTY_PRINT);
的最佳途徑,那麼我在這裏嘗試顯示JSON結果
首先和最重要的是:**停止**使用'mysql_'-函數,它們被棄用並且在PHP7.0中,**被移除**。改爲使用'mysqli_''或'PDO'。第二:你應該真正統一你的表命名約定。 'category_id','userID','userId'?三種不同的ID命名方案?這必然會引入錯誤。第三:你真的**是否希望選擇**所有**數據,並且每個**語句都運行,沒有任何過濾或減少?這會讓你的系統在一段時間後變得非常糟糕。 –
謝謝@FranzGleichmann,我一定會留意的。 –