Kohana 2.3.4 : MySQL query to JSON

350 views Asked by At

I am managing a project in Kohana 2.3.4 where I need to create an API for my android backend. What I am doing is send a query on my model which returns $result.

$query = "select product.deal_id,product.deal_key,p..."

$result = $this->db->query($query);

I am not sure if $result is an Object or and array This consists of 4 rows and 8 columns. I need to change $result to json format. I am currently doing this by echoing.

echo json_encode($result);

This return an empty json {}.

I am able to use the same query on my view by iterating through the $result

foreach ($result as $h){
        echo $h->main_key;
}

Am I doing this right or is it that my $result on this connection has no rows?

1

There are 1 answers

0
Zack On

I figured out I had use Kohana debug to know if my result was an object or an array. After calling the following

echo Kohana::debug($result);

I figured out that it was an object hence the empty result when converted to a json object. I had also tried getting an associative array with mysql_fetch_assoc which actually expected a mysql query object. This did not work as the object was created by my ORM object. I then solved this by calling

$result = $this->db->query($query)->as_array();

This returned an array and solved my problem.