Question

I am trying to return all selected data from mysql table. What I want is to return data in an array so that I will display that as json data. I acheived following so far but I do not know how ca I return that mysql data.

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

here where I am calling this method

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

here is what it echos

{"tag":"home","success":1,"error":0,"uid":null,"name":null,"profile_photo":null,"places":{"place_photo":null,"created_at":null}}
Was it helpful?

Solution

You need to define $data as an array first, besides that your code looks fine.

$data = array();

As you are, potentially, returning multiple rows you should be doing something like:

$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
  }
}

Take a look at to see the contents of your $data print_r($data);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top