普通网友 2015-01-18 16:42
浏览 14
已采纳

运行一个mysql foreach,其中一组值无效

I have an array with values like "849" and "584" or "275" etc and am running a mySQL query against each of these values. It appears to execute fine but I receive no values returned. What am I doing wrong here?

$content = "";
        foreach ($cookies_array as $key => $value){
            $sql_select_recent_items = $db->query("SELECT id, name FROM products WHERE id=".$key." LIMIT 0,10");

            $content .="".$sql_recent_activity_items["id"]." - ".$sql_recent_activity_items["name"]."<br>";

        }

When I do a var_dump on the array, it shows correctly like:

array(10) { [0]=> string(3) "852" [1]=> string(3) "856" [2]=> string(3) "720" [3]=> string(3) "783" [4]=> string(3) "784" [5]=> string(3) "785" [6]=> string(3) "708" [7]=> string(3) "716" [8]=> string(3) "717" [9]=> string(3) "749" }
  • 写回答

2条回答 默认 最新

  • douluyezhen4512 2015-01-18 17:20
    关注

    I'm assuming you are using either Mysqli or PDO as the $db.

    In both case the result of query() does return a "result class" where you need to fetch the value. It doesn't return a simple array containing your result.

    Mysqli fetch: http://php.net/manual/en/mysqli-result.fetch-assoc.php

    PDO: http://php.net/manual/en/pdostatement.fetch.php

    (There are exemples so it quite easy ;))

    So using Mysqli here a sample of what should work:

    $content = "";
            foreach ($cookies_array as $key => $value)
            {
                $result = $db->query("SELECT id, name FROM products WHERE id=".$value." LIMIT 0,10");
                while ($row = $result->fetch_assoc()) 
                {
                    $content .="".$row["id"]." - ".$row["name"]."<br>";
                }
            }
    

    NOTE1: I don't check for error, from documentation $result should be FALSE in those case. NOTE2: You MUST sanitize any parameter you append to your query ESPECIALLY if it come from the client. (A cookie is on the client part). Instead of

    "SELECT id, name FROM products WHERE id=".$value." LIMIT 0,10"
    

    it should look like

    "SELECT id, name FROM products WHERE id=".$db->real_escape_string($value)." LIMIT 0,10"
    

    NOTE3: I also recommand to batch your query for performance, you could use prepared statement ( http:// php.net/manual/en/mysqli.prepare.php and use bind_param as the sanitize your value or have multiple OR condition in your WHERE)

    NOTE4: I use $value in your query instead of $key because like other told you, $key is an index ("unique value" to get back the value from your array)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答