您好,在下面的代码中,您可以看到我的JSON返回的内容。
{"lifehacks":[{
"id":"2",
"URLtoImage":"http:\/\/images.visitcanberra.com.au\/images\/canberra_hero_image.jpg",
"title":"dit is nog een test",
"author":"1232123",
"score":"2",
"steps":"fdaddaadadafdaaddadaaddaadaaaaaaaaaaa","category":"Category_2"}]}
JSON返回的内容很好。唯一的问题是它只显示生命危险,如果它有一个或多个。那么我应该如何更改我的查询,以便显示没有喜欢的生活方式。
//Select the Database
mysql_select_db("admin_nakeitez",$db);
//Replace * in the query with the column names.
$result = mysql_query("select idLifehack, urlToImage, title, Lifehack.Users_fbId, idLifehack, steps, Categorie, count(Lifehack_idLifehack) as likes from Lifehack, Likes where idLifehack = Lifehack_idLifehack AND idLifehack > " . $_GET["id"]. " group by idLifehack;", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['idLifehack'];
$row_array['URLtoImage'] = $row['urlToImage'];
$row_array['title'] = $row['title'];
$row_array['author'] = $row['Users_fbId'];
$row_array['score'] = $row['likes'];
$row_array['steps'] = $row['steps'];
$row_array['category'] = $row['Categorie'];
//push the values in the array
array_push($json_response,$row_array);
}
echo "{\"lifehacks\":";
echo json_encode($json_response);
echo "}";
//Close the database connection
fclose($db);
我希望我的问题很清楚。提前谢谢你,我自己无法弄明白。
答案 0 :(得分:1)
您需要LEFT JOIN
。您的查询有INNER JOIN
。
select
idLifehack,
urlToImage,
title,
Lifehack.Users_fbId,
idLifehack,
steps,
Categorie,
count(Lifehack_idLifehack) as likes
from Lifehack
left join Likes on idLifehack = Lifehack_idLifehack
where idLifehack > whatever
group by idLifehack;
对不同的联接类型here有一个很好的解释。
还有几点......
在PHP中使用预准备语句。您的代码对SQL注入广泛开放,这已经破坏了职业生涯并导致数百万无辜的人窃取他们的个人信息。有很多网站展示了如何做到这一点,所以我不想在这里进入,但我会说我最喜欢的是bobby-tables。
避免在查询中使用隐式连接反模式。这是一个隐式连接:
FROM a, b
WHERE a.id = b.id
使用显式联接;他们将您的连接逻辑与过滤(WHERE
)逻辑分开:
FROM a
INNER JOIN b ON a.id = b.id