php json返回sql,php – 如何从我的特定SQL查询中返回json?
我有以下PHP代碼:
$servername = "host";
$username = "user";
$password = "passw";
$dbname = "dbname";
$conn3 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn3->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q3 = $conn3->prepare("SELECT c.one, c.two FROM table c");
$q3->execute();
if($q3->rowCount()>0)
{
$check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
$arr = array();
foreach ($check3 as $row) {
$arr[] = $row;
//how can I return json format here?
}
}
$conn2 = null;
?>
并且此查詢返回元素對(duì).但是我如何修改上面的代碼以獲得元素的json格式:
{key1:OSO; key2:AIKA}等
這樣我以后可以在jquery文件中使用它來打印它,具有以下功能:
$.getJSON('list.php', function(json) {
//assuming list.php resides with list.html directory
//console.log(json)
console.log(json.result.key1);
console.log(json.result.key2);
});
謝謝!
解決方法:
更改
SELECT c.one, c.two FROM table c
至
SELECT c.one as key1, c.two as key2 FROM table c
然后將結(jié)果封裝在json中(在foreach之后):
echo json_encode(array(
'result'=>$arr
));
但是你很可能需要在jquery中循環(huán)使用它們.
你的json輸出將是這樣的:
result: [
{'key1': 'asd', 'key2': 'qwe'},
[...]
{'key1': 'asd', 'key2': 'qwe'}
]
像他們一樣循環(huán)他們:
//first, see how it looks:
console.log(json.result);
jQuery.each( json.result, function( i, subresult ) {
console.log(subresult);
// you should be able to use: subresult.key1
});
標(biāo)簽:jquery,json,php,mysql
來源: https://codeday.me/bug/20190702/1359910.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的php json返回sql,php – 如何从我的特定SQL查询中返回json?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php-calendar,PHPCale
- 下一篇: java map 的复制,Java Ma