在返回查询结果时,哪种php循环在我的情况下更有效?

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."'");
    }

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

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.

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".

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.