我正在尝试将从数据库中获取的所有数据行编码为JSON,然后在客户端处理它,但我似乎无法使其工作。我的代码在下面
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output['original_title'];
$response['test'] = $output['content'];
return json_encode($response);
//return $output;
}
然后我尝试打印var_dump($ response),但我得到空值。虽然如果我var_dump($ output)我得到一个数组中的所有行..访问数组是这里的问题现在..i想想
注意:我正在使用PDO
答案 0 :(得分:1)
$ output是结果数组。使用循环或如果只有一行你需要这样做:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output[0]['original_title'];
$response['test'] = $output[0]['content'];
return json_encode($response);
//return $output;
}
答案 1 :(得分:1)
问题是$ output是一个你需要经历的数组。像:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response['text'] = $o['original_title'];
$response['test'] = $o['content'];
}
return json_encode($response);
}
}
这是最后一个回复,但是如果你想要全部,请执行:
function getTopic($conn){
$response = array('error'=>0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
}
return json_encode($response);
}
}
如果您只想要一行为MySQL语句添加限制。