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
Normally when using a prepared statement or a parameterized query you don't need to worry about delimiting string and date values; all of that is handled for you "behind the scenes".
I just tried the following and it worked for me:
<?php
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\Database1.accdb;' .
'Uid=Admin;Pwd=;';
$dbh = new PDO($connStr);
$sql =
"INSERT INTO tblDateTest (dateCol) VALUES (?)";
$newDateTimeValue = "2013-06-30 17:18:19";
$sth = $dbh->prepare($sql);
if ($sth->execute(array($newDateTimeValue))) {
echo "Done\r\n";
}
else {
$arr = $sth->errorInfo();
print_r($arr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With