0

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}}
1
  • getHome returns a multidimensional array. var_dump that array so you see what it looks like. You don't seem to now what datatypes your own functions returns. Commented Jun 2, 2012 at 11:34

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You're returning, potentially, multiple rows from the database but you are trying to access the data without looping through the returned row(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.