Reputation: 30471
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()');
Upvotes: 11
Views: 5050
Reputation: 562659
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.
Upvotes: 15
Reputation: 132031
No, because placeholders in prepared statements are automatically escaped. Thus in your case it will see, that it is a string and (at least) put it in quotes 'NOW()'
. Now its just a string for mysql for mysql too. You can set the current datetime using PHP
$sthandler->bindValue(1, date('c'));
Upvotes: 9