Welcome Guest, Not a member yet? Register   Sign In
Someone please explain ->row() vs ->result()
#1

[eluser]Sven Delle[/eluser]
OK, I'm bashing myself to death trying to pass data to a view!

I pull data from a model using:
Code:
$sql = "SOME QUERY HERE";
$query = $this->db->query($sql)->result(); // or ->row()

I'm pulling ONE single row from the db (based on ONE id).

Passing it on to a view like:
Code:
$data = $this->my_model->get_db_row();

or

$data['record_data] = $this->my_model->get_db_row();
$this->load->view('viewfile', $data)

Now depending on the situation I find myself pulling hair out, because I simply can't see why I in the have to sometimes use:

Code:
echo $variable_direct;

or

echo $variable_name->variable;

and other times:

echo $variable_name[0]->variable;

Can someone explain to me in simple terms what the different results are?

Maybe I'm just overtired after working 16 hours a day 26 days in a row ... you guess!
#2

[eluser]Samus[/eluser]
row() returns a single result.

result() returns multiple results in an array.

so use row() when you only need to return one result and result() when you have multiple.
#3

[eluser]Sven Delle[/eluser]
Thanks for clearing that out.

So that would mean if I had a query that returned multiple rows:

Code:
$sql = "QUERY RETURNING MULTIPLE ROWS";
$this->db->query($sql)->result();

Would return an array of stdClass objects, and:

Code:
$sql = "QUERY RETURNING MULTIPLE ROWS";
$this->db->query($sql)->row();

Would return a stdClass object? But which one? The first or the last row?

And wouldn't it be more clever to have the system return the same 'structure' (array for being able to wrap both a single and multiple rows) no matter how many records? That way I wouldn't have to check for this and that and figure out the right syntax before getting to the actual data?
#4

[eluser]Stefan Hueg[/eluser]
It would return the first row. The thing about the structure is just about expectation - result.

If you know that you can and will never get more then one result, row() is your function. If you don't know the actual number of results, result() is your function.

You have to keep an eye on which functions you use. row_array() is slightly faster than row(). If you get 1000 results and just want the very first one, don't rely on the active record functions row() and result(). What CodeIgniter does in case of row() is just:

-query 1000 results
-while-loop, fetching all the 1000 results
-return the first entry

You have two options for optimization:
-Optimize your SQL query by adding limits
-Fetch the results by yourself, like this

Code:
$result = $this->db->get('mytable');
while($row = mysql_fetch_assoc($result->result_id))
{
...
}

//or for a single result just one call of
$row = mysql_fetch_assoc($result->result_id)
#5

[eluser]Sven Delle[/eluser]
Thanks a lot for clearing this out.




Theme © iAndrew 2016 - Forum software by © MyBB