我正在尝试从mysql表中返回所有选定的数据。我想要的是返回数组中的数据,以便我将其显示为json数据。到目前为止我实现了以下但我不知道如何返回那个mysql数据。
public function getHome() {
$result = mysql_query("SELECT * FROM places") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
} else {
// user not found
return false;
}
}
这里我称这个方法为
if($db->getHome()) {
$data = $db->getHome();
$response['success'] = 1;
$response['uid'] = $data['uid'];
$response['name'] = $data['name'];
$response['profile_photo'] = $data['profile_photo_path'];
$response['places']['place_photo'] = $data['place_photo_path'];
$response['places']['created_at'] = $data['created_at'];
echo json_encode($response);
} else {
echo "bye";
}
这就是回声
{"tag":"home","success":1,"error":0,"uid":null,"name":null,"profile_photo":null,"places":{"place_photo":null,"created_at":null}}
答案 0 :(得分:3)
您需要先将$ data定义为数组,此外您的代码看起来还不错。
$data = array();
正如您所知,可能会返回多行,您应该执行以下操作:
$data = $db->getHome(); // There's no need to call this twice
if($data) {
foreach($data as $place) {
// Do what you need to do with each place here
}
}
查看$ data print_r($data);