Francisco Albert
Francisco Albert

Reputation: 1721

json_encode makes nothing in my php

I've this small code, I know I receive fine from the database because I made some print_r and work fine:

//build query SQL         
$query = $this ->select() 
    ->where('numBedrooms=?',$numBedrooms) 
    ->where('type=?',$type)
    ->where('state=?',$state)
    ->limit(8);//8 rows, with an offset of $recent_page*8-8
//execute query SQL
$rows=$this->fetchAll($query);
//encode json
$var= json_encode($rows);//-------->var is empty always!!

Upvotes: 4

Views: 330

Answers (3)

Drew Anderson
Drew Anderson

Reputation: 542

To add a different answer to this...

Zend provides different ways of accessing data. I find it easier to always work with arrays in Zend as it makes your code more portable.

Using Zend_Db_Table_Abstract:

class Model_MyStuff extends Zend_Db_Table_Absract
{
    protected $_name = 'Stuff';
    protected $_primary = 'StuffID';

    function getStuff()
    {
        $select = $this->select();

        $select->where('Active = 1');

        $results = $select->query()->fetchAll();
        if (count($results) > 0) return $results;
        return null;
    }
}

This code will return an array instead of objects which can immediately be passed into json_encode. The difference is you're asking the object to fetchAll($query) whereas I'm asing the select to query()->fetchAll(). I believe the select object needs to come from $this->select() for this to work however.

Upvotes: 3

Ben
Ben

Reputation: 21249

You need to convert your row set to an array:

$var= json_encode($rows->toArray());

See Retrieving a Rowset as an Array on http://framework.zend.com/manual/en/zend.db.table.rowset.html

Upvotes: 4

MasterGberry
MasterGberry

Reputation: 2860

If fetchAll() is returning an object like you say it is, then it would be wise to first convert this to an array and then to pass it to json_encode. I do not believe json_encode work's with objects.

Upvotes: 0

Related Questions