problem when using a while loop |
[eluser]Spleshmen[/eluser]
hello all.i am new to codeigniter and i am trying to learn how to use this framework in the user guide i see all database examples are with foreach loops and i tried to make one with a while loop but its not working,maby you can tell me where i did wrong.thanks here is my model (site_model.php): Code: <?php Code: <?php Code: <?php Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes) in ... Thanks
[eluser]vickel[/eluser]
The error lies in your model. Change the if clause for this: Code: if ($query->num_rows>0)
[eluser]Ben Edmunds[/eluser]
First, if foreach works, why not use it? Are you saying you're getting the memory error on foreach? Second, in your model just return $query->result_array(). There is no need for you to manually convert the object to an array.
[eluser]Spleshmen[/eluser]
i just want to learn how to use it with the while statement to, not just the foreach. let me put it this way : why this code its working Code: foreach($query->result() as $row) { Code: while($row = $query->result()) {
[eluser]BrianDHall[/eluser]
http://ellislab.com/codeigniter/user-gui...sults.html Quote:result() So what happens in a foreach is on the first call $query->result() gives an array of objects. PHP saves this array for the loop to use, and then it iterates through each array element in turn, assigning the value to $row as it goes through. Note that in your first foreach example there is no difference in doing that vs doing $data = $query->result() directly. As to the while() example, on every execution of the while() loop you assign $row an array of result objects. You then assign the entire result set to an array element of $data[], and then you start all over again. So rather than build up $data with an array of result objects, you are actually building up an array where each element in the array is itself and array containing every result. So if you have 100 results returned, rather than end up with an array of 100 results you end up with a multi-dimensional array of objects that effectively contains 10,000 results, and at any given time you are throwing them around quite a bit. So its very easy to trip the allocated memory array doing something like that. To answer your question as to how to use the functions in a while() loop...don't. ![]() The only way it works is something like this: Code: $i = 1; Which is rather messy, but I suppose it could come in handy at some point. The row() function does not automatically iterate through the results, thus the need for $i.
[eluser]Spleshmen[/eluser]
thanks for the explaination.its all clear now ![]() |
Welcome Guest, Not a member yet? Register Sign In |