Question

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.

Was it helpful?

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'];
}

OTHER TIPS

You should be aware that you're actually building the Database_Query object, so there has to be something to execute it in the end, right?

$results = DB::select('*')->from('table')->execute();

and then you can normally loop through these:

foreach ($results as $result) { echo $result->id; }

To get row:

$query = DB::select('p.id')
            ->select_array(array('p.title', array('p.title', 'pocket') ))
            ->from(array($this->_table_name, 'p'))
            ->limit(1);

echo $query->execute()->get('id');

To show query:

echo $query->compile();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top