gpt4 book ai didi

php - 将连接的数据从mysql输出到json作为json对象

转载 作者:行者123 更新时间:2023-11-29 01:52:43 24 4
gpt4 key购买 nike

这是我的数据库:

enter image description here

我正在尝试将 to_id 为 4 的所有 from_id 获取到一个 json 对象,在该对象中,我能够显示来自按不同 time_sent 排序的堆栈中的 from_id 的所有消息

我试过:

代码:数据库查询类(在数据库类中)

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 中

    $message = new Message();
$results = $message-> getadminMessage();
echo json_encode($results);

然后我使用getjson

$.getJSON("http://127.0.0.1/tum_old/custom/php/getadminmsg.php",

function(response){
console.log(response);

});

在我的日志中我得到

enter image description here

数据似乎是组连接的,但我也希望各种消息采用对象形式,即将消息显示为对象,这样我就可以轻松地做到:

data.object[0].from_id[0].msg 获取 TRUE LOVE 作为消息

科学::::

enter image description here

最佳答案

选择你需要的

$sql = "SELECT group_concat(messg) as msg, time_sent, from_id
from {$this->_table} where to_id = 4 group by from_id";

对于服务器端你需要json_encode数组

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);
}

关于php - 将连接的数据从mysql输出到json作为json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com