Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Retrieve single column using DB class?
  • There HAS to be a way to do this, but I can't find a way to do it anywhere. I've been doing something like $current = \DB::select('field')->from('table')->where('id', \Input::get('id'))->execute()->current(); $field = $current['field'];, but it's starting to bug me. 

    How would I just retrieve a single column from the database in one line? Especially if it's something like \DB::select(\DB::expr('COUNT(*)'))...

    I'm sure I've just overlooked this somewhere, so if someone could point me in the right direction it would be much appreciated.

    Thanks
  • HarroHarro
    Accepted Answer
    To count records, simply use DB::count_records('table').

    execute() always returns a resultset, even if the resultset only contains one row. It's better to be consistent then having to take into account that the returned value might be different based on the number of rows in the resultset. That would result in more complex code.

    The resultset (which a Database_Result type object) has a method called get(), which allows you to fetch a field from the current row.

    So you can do:

    $field = \DB::select('field')->from('table')->where('id', \Input::get('id'))->execute()->get('field', 'defaultvalue');

  • Perfect, thanks. I knew about get but always figured it returned an array of those values. I didn't consider that if there was one result it would return that single value.

    Does DB::count_records allow chaining with all of the query builder methods? (where, or_where, etc)?
  • No, you can't, it's a special method that constructs a count query and returns the result.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion