Binding a date string parameter in an MS Access PDO query

Posted by harryg on Stack Overflow See other posts from Stack Overflow or by harryg
Published on 2013-07-01T15:54:23Z Indexed on 2013/07/01 16:21 UTC
Read the original article Hit count: 347

Filed under:
|
|
|

I've made a PDO database class which I use to run queries on an MS Access database. When querying using a date condition, as is common in SQL, dates are passed as a string. Access usually expects the date to be surrounded in hashes however. E.g.

SELECT transactions.amount FROM transactions WHERE transactions.date = #2013-05-25#;

If I where to run this query using PDO I might do the following.

//instatiate pdo connection etc... resulting in a $db object
$stmt = $db->prepare('SELECT transactions.amount FROM transactions WHERE transactions.date = #:mydate#;'); //prepare the query
$stmt->bindValue('mydate', '2013-05-25', PDO::PARAM_STR); //bind the date as a string
$stmt->execute(); //run it
$result = $stmt->fetch(); //get the results

As far as my understanding goes the statement that results from the above would look like this as binding a string results in it being surrounded by quotes:

SELECT transactions.amount FROM transactions WHERE transactions.date = #'2013-05-25'#;

This causes an error and prevents the statement from running.

What's the best way to bind a date string in PDO without causing this error? I'm currently resorting to sprintf-ing the string which I'm sure is bad practise.

Edit: if I pass the hash-surrounded date then I still get the error as below:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22018]: Invalid character value for cast specification: -3030 [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. (SQLExecute[-3030] at ext\pdo_odbc\odbc_stmt.c:254)' in C:\xampp\htdocs\ips\php\classes.php:49 Stack trace: #0 C:\xampp\htdocs\ips\php\classes.php(49): PDOStatement->execute() #1 C:\xampp\htdocs\ips\php\classes.php(52): database->execute() #2 C:\xampp\htdocs\ips\try2.php(12): database->resultset() #3 {main} thrown in C:\xampp\htdocs\ips\php\classes.php on line 49

© Stack Overflow or respective owner

Related posts about php

Related posts about sql