0

我正在尝试从 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}}
4

1 回答 1

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

于 2012-06-02T11:15:26.983 回答