douwei1930 2013-09-25 07:43
浏览 54
已采纳

php:无法迭代每个循环

I am facing the follow error from the below code:

Error:

Warning: Invalid argument supplied for foreach() 

Code:

 //--------This is the code for jquery UI autocompleter-------------

include "inc/connect.php";
$skeyword = $_GET["term"];
$req = "SELECT  p.prm_title ,a.am_name, c.cm_name ,l.lm_name ,b.bm_name,r.pm_name  "
    . "FROM product_master p,author_master a,category_master c,language_master l,binding_master b ,publisher_master r "
    . "WHERE p.prm_title LIKE '%$skeyword%' OR a.am_name LIKE '%$skeyword%'
       OR c.cm_name LIKE '%$skeyword%' OR l.lm_name LIKE '%$skeyword%' OR b.bm_name LIKE '%$skeyword%' OR r.pm_name LIKE '%$skeyword%'  
       GROUP BY p.prm_id LIMIT 10";

$res = mysql_query($req);
$ret = array();
foreach (mysql_fetch_array($res) as $row) {
    foreach ($row as $val) //--Error: from this line, Why?
    {
        if (false !== stripos($val, $skeyword)) {
            $ret[] = $val;
            break;
        }
    }
}

$testme = json_encode($ret);
echo $testme;

The above code is written for jquery auto-completer to search in many column field, but it will return only the matched column.

Please help me to solve this issue..

  • 写回答

5条回答 默认 最新

  • duanquan1876 2013-09-25 07:55
    关注

    why:

    If a variable:

    • is not array
    • does not implements the interface Iterator

    and it is used to iterator by foreach, this error will raise.


    How to fix

    mysql_fetch_array returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows, so use a while loop to fetch result:

    while ($row = mysql_fetch_array($res))
    {
        // if $row is false, the code will not hit here.
        foreach ($row as $val)
        {
            if (FALSE !== stripos($val, $skeyword))
            {
                $ret[] = $val;
                break;
            }
        }
    } 
    


    update:

        while ($row = mysql_fetch_array($res))
        {
            // if $row is false, the code will not hit here.
            foreach ($row as $val)
            {
                if (FALSE !== stripos($val, $skeyword) && !in_array($val, $ret))
                {
                    $ret[] = $val;
                    break;  // what this break for?
                }
            }
        } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程