在mysql表中我有一组记录。我想把它们想要在json响应下面显示出来。
"results":[
{
"timestamp":"2014-03-04 17:26:14",
"id":"440736785698521089",
"category":"sports",
"username":"chetan_bhagat",
"displayname":"Chetan Bhagat"
}
我从数据库获得了上面的值,即时间戳,id,类别,用户名。如何以上面的json响应形式显示结果?
更新:
我以这种方式获取数据:
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
while ($row = @mysqli_fetch_array($result))
{
$url = $row['url'];
$img_url = $row['img_url'];
$screen_name = $row['screen_name'];
}
答案 0 :(得分:1)
以传统方式获取结果:
$data['results'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
然后将其全部转换为JSON。 BAM!
$results = json_encode($data);
这比在SQL查询中尝试格式化JSON要容易得多。
有关详情,请参阅:
由于您使用mysqli而不是PDO,并以过程方式使用它,因此您将以不同的方式获取行:
while ($data['results'][] = mysql_fetch_assoc($result));
然后你可以像我上面所示的那样json_encode()。
答案 1 :(得分:1)
试试这个......
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
while ($row = @mysqli_fetch_array($result))
{
json_encode($row);
}