Reputation: 13663
I'm new to CodeIgniter. I love it, it's great, but one issue cannot resolve for days.
I'm trying to get a single row, by its id, like this :
$query = $this->db->get_where('content', ['id' => $id]);
$the_content = $query->result_array();
However, it results in an array of size 1, like this:
$the_content = [ 0 => ['id' => 1, 'content'=> 'abc']];
so I always have to convert it to its first element like this:
$the_content= $the_content[0];
But you can understand why I don't like this.
I also tried $query->result();
, still the same.
I'm sure I'm missing a simple point here, but what?
How do I get single element from ActiveRecord instead of array?
Upvotes: 1
Views: 4994
Reputation: 76636
Use first_row()
:
$row = $query->first_row();
If you want an array instead:
$row = $query->first_row('array')
Or if you want a specific row returned you can submit the row number as a digit in the first parameter:
$row = $query->row_array(3);
If you want to get the field of the first row:
$field = $query->first_row()->field;
echo $field;
See the documentation here.
Upvotes: 3
Reputation: 7475
The solution would be:
$the_content = $query->row_array();
To return a single dimentional array. To retrieve you would write:
echo $the_content['content'];
Upvotes: 3
Reputation: 2289
There is a function to get the first row from query:
$the_content = $query->first_row('array')
ref: http://ellislab.com/codeigniter/user-guide/database/results.html
Upvotes: 1