Welcome Guest, Not a member yet? Register   Sign In
call query results without foreach
#1

[eluser]Corbee[/eluser]
Hi,

I happened to only need to get one data in a database, how do I do it without calling a foreach?

Thanks
#2

[eluser]Corbee[/eluser]
Also I forgot to mention that I'm using a data returned from the model with the ff code

model
Code:
foreach ($q->result_array() as $row)
            {
                $data[] = $row;                
            }
            $q->free_result();
            return $data;

will
echo $item['field1'];

work in this?

Code:
$item = $this->Model->getdata($thedata);

or are there better ways

Thanks
#3

[eluser]Corbee[/eluser]
okay, I finally got to test it on a computer, only to find out that it didn't work.

Where did I got wrong?
#4

[eluser]trumpetnl[/eluser]
Think OO :-) !
The OBJECT you create by retrieving data from the database has METHODES. One of these methodes is the result_array() methode, another one is the row() methode.

If you want to perform tasks on an array of result (the result of using the methode result_array()) you can use your foreach loop (you have (likely more then one result and want to cycle thru the array, hence you LOOP).
Code:
foreach ($q->result_array() as $row)
            {
                $data[] = $row;
            }

When you only want to work with the first row of the result you can use
Code:
$data = $q->row();

So, in your case, drop the foreach loop altogether and put in
Code:
$data = $q->row();
return $data;


Granted, this object/array thingy can be confusing, just remember, when using the database library, your result is an OBJECT with properties and methodes. Think OO and all will fall into place (at least for me it did Smile

hope this helps
#5

[eluser]WanWizard[/eluser]
It is even more confusing

The object has a property called 'result_array', which is an array holding all results, and a method called 'result_array()', which fills the property and returns it. It also has a property called 'result_object', and a method called 'result_object', which does the same, but then creates an array of objects. And finally you have the methods to request a single row, that can return an object or an array depending on how you call it.

The first time the method is called, the data is fetched and stored in the property. All other calls then use the property to return the data.

So you can call $object->first_row(), which will create the result_object property. After that, you can loop over $object->result_object without calling the method.




Theme © iAndrew 2016 - Forum software by © MyBB