1

I have this function in my model:

public function get_current_knowledge($account_id)
{
    $query = $this->db->query('SELECT * FROM knowledge WHERE account_id = ?', array($account_id));

    return $query->result_array();
}

I used to access it like this:

while ($record = $this->synchronization_model->get_current_knowledge($account['id'])) {
    print_r($record);
}

But strangely, my page would timeout probably because the while results in a neverending loop or something? But why is the question.

I noticed that foreach does work. But essentially this should return the same as while right? When accessing it like this, using foreach:

foreach ($this->synchronization_model->get_current_knowledge($account['id']) as $row)
{
     print_r($row);
}

1 Answer 1

1

The while() loop runs for as long as whatever is inside the parentheses is truthy.

You're assigning the value of $this->synchronization_model->get_current_knowledge($account['id']) to the variable $record every time the loop runs. Of course, the variable has a value (since you're assigning it), and so its always truthy. That's where you get your infinite loop.

Sign up to request clarification or add additional context in comments.

4 Comments

But I used the while loop before I converted this code to codeigniter style. Like, while($record = pg_fetch_array(..) and in that time it used too work. I'm a bit confused.
I think it would break out of the loop if $record was assigned a false value. It's hard for me to get the bigger picture of how your code previously behaved.
Yeah, I looked up pg_fetch_array on PHP.net. It returns false when the last row is returned. Apparently this does not happen when using the code I'm know using. Deciedd to switch to foreach where I previously used while. That should yield the same results right? Thanks for your help.
Should do. You're welcome! Remember to mark my answer as correct if it helped you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.