Search code examples
phpkohanakohana-3kohana-db

Database query in Kohana only shows the SQL and not the result rows


I just started to using the Kohana framework and I'm trying to execute a few queries, but after spending a couple hours in documentation and running some tests all I have is this:

class Controller_Test extends Controller {
    public function action_index()
    {
       $query = DB::select()->from('test')->where('test', '=', '1');
       echo $query  
    }
}

Now, if try to run this all it does is echo my SQL.

How do I get the actual data from my database? I know that I could do something like:

$row = mysql_fetch_row(mysql_query($query));
echo $row[0];

and it would work; but I guess that's just completely stupid, since I'm using a framework and there has to be built-in method(s) for this.


Solution

  • After you've built up the query you'll then need to turn that into a Database_Query object using the execute() method so you can get values to run through.

    If you want to deal with the results of the query as an array, you can add the as_array() method after the execute like so:

    $query = DB::select()->from('test')->where('test', '=', '1')
                         ->execute()->as_array();
    

    If you're only dealing with a single row, and you know you only need a single row, you can change that to current():

    $query = DB::select()->from('test')->where('test', '=', '1')
                         ->execute()->current();
    

    Then you can extract as needed when you loop through the array:

    foreach ($query as $row)
    {
        echo $row['title'];
    }