3

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?

Zack
  • 1,527
  • 2
  • 20
  • 32
  • Maybe the ->query bombed or no rows in resultset. How can we tell – AsConfused Jun 09 '15 at 04:54
  • @AsConfused Hi, I have tested the sql query, as I stated it returns 4 rows and 8 columns on phpmyadmin. Also `$this->db` is my `Database` object. – Zack Jun 09 '15 at 04:57
  • But we aren't on phpmyadmin now are we – AsConfused Jun 09 '15 at 05:00
  • @AsConfused yes of course. So what would be the causing the ->query to 'bomb' or not return results if this is the same query I am using on my View? – Zack Jun 09 '15 at 05:02
  • Not much code to look at. No error traps to see. Dont even know if u have a connection. – AsConfused Jun 09 '15 at 05:04
  • 1
    I quick look reveals that Kohana (v3) is using PDO so after doing a call to PDO::query, you don't get the tuples as array/objects. You get a PDOStatement on which you have to do fetch or fetchAll on. See PDOStatement::fetch for details. `$result = $this->db->query($query)->fetchAll(PDO::FETCH_ASSOC);` – Basti Jun 09 '15 at 05:59
  • 2
    @Basti thank you, I figured out my problem using your suggestion. Instead of `fetchAll` all I had to do is call `as_array()` – Zack Jun 09 '15 at 06:26

1 Answers1

4

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.

Zack
  • 1,527
  • 2
  • 20
  • 32