Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 368
Travis Avatar asked Jun 24 '10 09:06

Travis


People also ask

What is PDO prepared statement?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

What function do you use to run a query using a PDO object?

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

What is PDO parameter binding?

Parameter binding is essential for protecting your web application from SQL-injection. Pretty much all data which is going to be used in SQL statement needs binding. Binding simply saying is just a way to tell engine that a particular piece of data is a string, number, character and so on.

Why we use prepare method instead of query in PHP PDO statement?

Prepared statements reduce parsing time as the preparation on the query is done only once (although the statement is executed multiple times) Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query.


1 Answers

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.

like image 50
Naktibalda Avatar answered Sep 25 '22 15:09

Naktibalda