user837032
user837032

Reputation: 84

Which php loop is more effective in my case, when returning query results?

Which one of these two is better in my case?

While loop:

function search_hotel($searchterm)
        {
    $query = $this->db->order_by("id", "desc")->like('name', $searchterm)->get('hotel_submits');
            $data = array();
            while($row = mysql_fetch_array($query))
            {
               $data[] = $row->name;
            }
            return $data;
}

Foreach loop:

function search_hotel($searchterm)
    {
        $query = $this->db->order_by("id", "desc")->like('name', $searchterm)->get('hotel_submits');
        $data = array();
        foreach ($query->result() as $row)
        {
           $data[] = $row->name;
        }
        return $data;             
        //return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'");
    }

Upvotes: 0

Views: 374

Answers (4)

mermshaus
mermshaus

Reputation: 646

When using a framework and its custom DB adapter class, it seems pointless to switch back to PHP's built-in functions in the middle of a script. Even if CI's adapter and PHP's mysql_* functions might be using the same DBMS connection library (mysql).

I strongly recommend to stick with Code Igniter's version (foreach ($query->result() as $row)). From a performance point of view, there shouldn't be any noticeable differences. Regarding the application architecture, it certainly is much cleaner not to mix the access interfaces. Although it might work out, it might also cause problems.

Upvotes: 1

Marc B
Marc B

Reputation: 360872

It would appear you're mixing up mysqli and mysql syntax. The two libraries are NOT compatible internally. You cannot use a handle/statement in one and consume it in another. Both libraries maintain completely independent connections to the database.

That'd mean the first one will be faster, since mysql_fetch_array() will fail and the inner loop will never run. But faster doesn't mean "right".

Upvotes: 0

afaf12
afaf12

Reputation: 5436

In your case, result returned by query is array. Which means you can use foreach statement or while statement.

Just note that foreach statement is optimized for working with arrays (and as of PHP5, objects as well) and is faster than while statement. While can be used to achieve the same effect but it is not as efficient if you want to go through all elements of the array.

Upvotes: 1

wanovak
wanovak

Reputation: 6127

while is technically more efficient than foreach, but it's not worth comparing: they're both pretty much identical in this case.

Upvotes: 3

Related Questions