将连接数据从mysql作为json对象从mysql输出到json [英] Outputting concatenated data from mysql to json as json object
问题描述
这是我的数据库:
我试图将to_id为4的所有from_id获取到一个json对象,该对象无法按其不同的time_sent排序显示堆栈中来自from_id的所有消息
Am trying to get all from_id which to_id is 4 to a json object where ill be able to show all messages from a from_id in a stack sorted by their different time_sent
我尝试过:
代码: 数据库查询类(在DBASE类中)
CODE: DATABASE QUERY CLASS(THIS IS IN THE DBASE CLASS)
public function query($sql){
$this->_last_query = $sql;
$result = mysqli_query($this->_conndb, $sql);
$this->displayQuery($result);
return $result;
} // end of query
public function displayQuery($result){
if(!$result){
$output = "database query failed :". mysqli_error($this->_conndb);
$output .= "last sql query was: ".$this->_last_query;
die($output);
}
else{
$this->_affected_rows = mysqli_affected_rows($this->_conndb);
}
} //End of query results
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
while($row = mysqli_fetch_assoc($result)){
$out[] = $row;
}
mysqli_free_result($result);
return $out;
}
消息分类:
private $_table = 'messages';
public function getadminMessage(){
$sql = "SELECT group_concat(messg, time_sent, from_id) as from_id from {$this->_table} where to_id = 4 group by from_id";
return $this->db->fetchAll($sql);//IN THE DBASE CLASS ABOVE
}
在文件getadminmessage.php
In the file getadminmessage.php
$message = new Message();
$results = $message-> getadminMessage();
echo json_encode($results);
然后我使用getjson
I then use getjson
$.getJSON("http://127.0.0.1/tum_old/custom/php/getadminmsg.php",
function(response){
console.log(response);
});
在我的日志上,我得到
数据似乎是串联在一起的,但是我也希望各种消息以对象形式出现,即消息将被显示为对象,这样我就可以轻松做到:
The data seems group concatenated but i would also like the various messages to be in object form that is the messages to be displayed as objects such that i can easily do:
data.object [0] .from_id [0] .msg获得真爱"作为消息
data.object[0].from_id[0].msg to get TRUE LOVE as the message
推荐答案
选择
$sql = "SELECT group_concat(messg) as msg, time_sent, from_id
from {$this->_table} where to_id = 4 group by from_id";
对于服务器端,您需要json_encode数组
for server side you need json_encode the array
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
$cnt =0;
while($row = mysqli_fetch_assoc($result)){
$out[$cnt]['msg'] = $row['msg'];
$out[$cnt]['time_sent'] = $row['time_sent'];
$out[$cnt]['from_id'] = $row['from_id'];
$cnt++;
}
mysqli_free_result($result);
return json_encode($out);
}
这篇关于将连接数据从mysql作为json对象从mysql输出到json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!