PDO positional and named parameters as part of the same prepared query?

非 Y 不嫁゛ 提交于 2019-12-18 19:37:57

问题


I'm learning the ropes with PDO.

Here is my sql (the number of parameters that can appear in the WHERE is variable).

    SELECT
        ID, title

    FROM
        table

    WHERE
        something = ?

    ORDER BY 
        :sort :dir 

    LIMIT 
        :start, :results

Here is my code:

        $query = $conn->prepare($sql);

        if ($parameters) {

            $i = 0;
            foreach ($parameters AS $parameter) {

                $i++;
                $query->bindParam($i, $parameter);

            }

        }

        $query->bindParam(':start', $pagination['start'], PDO::PARAM_INT);
        $query->bindParam(':results', $pagination['results'], PDO::PARAM_INT);
        $query->bindParam(':sort', $pagination['sort']);
        $query->bindParam(':dir', $pagination['dir']);

        $query->execute();

... and here is the exception that it generates:

 Invalid parameter number: mixed named and positional parameters

Is it impossible to combine positional and named parameters in the same query? Or am I missing something?

Thanks!


回答1:


Yes, it's impossible.

PDO.prepare

You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style.




回答2:


Use a wrapper function, a naive replacement function will suffice.

if (strpos($sql, ":")) {
    $i = -1;
    while (strpos($sql, "?") && isset($parameters[++$i])) {
        $parameters[":p$i"] = $parameters[$i];
        unset($parameters[$i]);
        $sql = preg_replace("/[?]/", ":p$i", $sql, 1);
    }
}

Mix $sort and $dir directly into the $sql query. These two are SQL identifiers, not data.



来源:https://stackoverflow.com/questions/3108571/pdo-positional-and-named-parameters-as-part-of-the-same-prepared-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!