【问题标题】:Myslqi stmt bind param not working properlyMyslqi stmt 绑定参数无法正常工作
【发布时间】:2013-11-17 22:23:12
【问题描述】:

我是新的 PHP 5 mysqli 的新手,但我已经用老式的方式做了很多工作。

这是我的代码

$query = "SELECT `id`, `catn`, `name`, `name_en`, `image`, `price`, `old_price`, `cat` FROM `products` WHERE `show` = 'Yes'";
        if (!empty($order)) {
            $params[0] = $params[0] . "s";
            $query = $query . " ORDER BY ? ".$way;
            $params[] = $order;
        }
        $stmt = $this->db->prepare($query);

        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($params as $key => $value)
                $refs[$key] = &$params[$key]; 
        } 

        if ($stmt) {
            call_user_func_array(array($stmt, 'bind_param'), $refs);

            $stmt->execute();
... more code below

$way 变量始终为 ASCDESC。但是查询给了我按 id 排序的结果(就像没有 ORDER BY 语句一样)。所以查询写在bind_param 之前所以我猜参数没有正确绑定?你能告诉我哪里出错了

【问题讨论】:

    标签: php mysql mysqli sqlbindparameter


    【解决方案1】:

    我认为您没有正确使用bind_param,因为您排除了必须首先出现的$types 参数。但是,这些用于参数(例如show = ? 的值)。您不会对查询结构的某些部分(例如关键字)使用参数。您必须将字符串连接到查询本身。如果您担心安全性,请明确进行连接,例如

    if ($way == 'ASC') {
        $query .= "ASC";
    }
    else {
        $query .= "DESC";
    }
    

    bind_param 将在参数周围添加引号,使查询无效 (ORDER BY 'ASC')

    【讨论】:

    • ? 用于命名我想要对结果进行排序的字段.. 这仍然不正确吗?我现在就试试你说的:)
    • @Bankin 我现在明白了。是的,这是一个类似的问题。您不能将 ? 用于 MySQL 结构,如关键字、表、列等。
    【解决方案2】:

    如果您使用参数编写 ORDER BY 子句,您将搜索固定的文字字符串,例如你会得到这个:

    ORDER BY 'price' DESC
    

    ... 而不是这个:

    ORDER BY price DESC
    

    你不能use parameters to provide identifiers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2013-04-03
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多