为什么 BindValue 在使用 WHERE 子句时不会产生结果


Why BindValue does NOT yield results when WHERE clause is used?

我不知道我在这里做错了什么。如果我在此查询中省略 WHERE 子句,服务器将返回数据库中的所有行。所以我知道这部分有效。 如果我使用 WHERE 子句,即

其中名称='$name' 和 loc='$loc' -

我得到结果,但是当我使用 bindValue 或在执行命令中传递绑定器时,我没有收到错误,也没有数据

    $stmt = "SELECT * FROM table1 LEFT JOIN table2 ON table1.ID=table2.fkID".
            " WHERE name = :name AND loc = :loc";
    $binder = array(':name' => $name, ':loc' => $loc);

这如果采用这些参数的函数

public function fetchData($stmt, $binder = array())
    {
        $DB = new PDO(........);
        $STMT =  $DB->prepare($stmt);
        foreach ($binder as $key => $value):
            $k = (is_numeric($key)) ? $key + 1 : $key;
            if (is_int($value)):
                $STMT->bindValue($k, (int) $value, PDO::PARAM_INT);
            else:
                $STMT->bindValue($k, $value, PDO::PARAM_STR);
            endif;
        endforeach;
        try {
            $STMT->execute();
            return $STMT->fetchAll(PDO::FETCH_ASSOC);
        }
        catch (PDOException $e) {
            die($this->error = $e->getMessage());
        }

我在这里做错了什么。对不起,伙计们,我搜索了所有类似的问题,但我没有答案。

我通过再次重写代码来解决此问题:

foreach ($binder as $key => $value):
            $k = (is_numeric($key)) ? $key + 1 : $key;
            $v = $value;
            if (is_int($v)):
                $STMT->bindValue($k, (int) $v, PDO::PARAM_INT);
            else:
                $STMT->bindValue($k, $v, PDO::PARAM_STR);
            endif;
        endforeach;

请注意 foreach 语句中使用的$v,而不是原始$value;