Related question, but not helpful to me: Why cant you pass MYSQL functions into prepared PDO statements?
Here’s the deal: I’m writing an abstraction layer to PHP PDO and implementing a query builder.
This exact problem is occurring only in INSERT statements. Here’s an example of my code:
$db->insert('table_name')
->keys(array('abc', 'def', 'ghi'))
->values(array($var1, $var2, $var3)) // can take a 2D array if you want to insert multiple rows at the same time
->execute();
The underlying code builds the query string with ?’s instead of values. For this particular example the query would result in the following:
INSERT INTO `table_name`
(`abc`, `def`, `ghi`)
VALUES
(?, ?, ?)
Upon calling execute(), it passes the values to PDOStatement::execute() as single dimension array (i.e. all values associated with the question marks are put in a single array). And this is where the problems start – the PDOStatement::execute() does not process MySQL functions as such, but quotes them as strings, thus breaking the query:
INSERT INTO `table_name`
(`abc`, `def`, `ghi`)
VALUES
('123', 456, 'NOW()') -- error, incorrect datetime value: 'NOW()'
The question is – how do I make this work while still maintaining the same interface? I know I could just check if the value of the column is a MySQL function and put it in directly instead of the question mark, but there are many functions one could use there and that would suck.
Edit: so it seems that for now the easiest option would be to simply set the values to leave alone like this: $var3 => 'noquote'. It’s not really a good one, but it works.
Add another argument for that method:
Keep in mind, that you cannot use ‘?’ when you want to do access the columns, e. g. in
COLUMN1 + 1orCOLUMN1 + COLUMN2.