Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO: Pass a MySQL function to bindValue/bindParam

Tags:

php

mysql

pdo

Is it possible to insert MySQL functions using bindValue()? My code below just gets outputted as the string 'NOW()' instead of the function NOW() (without quotes).

$sthandler->bindValue(1, 'NOW()');
like image 567
enchance Avatar asked Jan 02 '12 18:01

enchance


1 Answers

No. A query parameter substitutes only for a single constant value. For example, a numeric constant or literal string or date.

Anything else -- column names, table names, SQL keywords, functions, expressions -- must be in the SQL string at parse time.


Re your comment:

You should understand that parameters are not just a convenience to interpolate extra strings into your SQL. PREPARE is analogous to a compile phase for Java or C#, whereas EXECUTE is analogous to running the compiled code.

Prepare time is when the RDBMS does syntax checking, and also validation of references. It must give an error if you name a table that doesn't exist, or invoke a function that doesn't exist.

You can't pass table names or function calls as parameters because then the RDBMS wouldn't be able to validate those references at prepare time. You shouldn't be able to use a query parameter to change the syntax of the statement, or introduce invalid tables or functions.

So the parameter placeholder must be an irreducible syntactic element that is never an invalid reference, i.e. a single literal value -- a number or a string.

like image 143
Bill Karwin Avatar answered Sep 23 '22 18:09

Bill Karwin