在MS Access PDO查询中绑定日期字符串参数


Binding a date string parameter in an MS Access PDO query

我制作了一个PDO数据库类,用于在MS Access数据库上运行查询。当使用日期条件进行查询时,正如SQL中常见的那样,日期是作为字符串传递的。Access通常希望日期被散列包围。例如

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

如果我在哪里使用PDO运行此查询,我可能会执行以下操作。

//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

据我所知,上面的结果是这样的,因为绑定字符串会导致它被引号包围:

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

这会导致错误并阻止语句运行。

在PDO中绑定日期字符串而不导致此错误的最佳方法是什么?我目前正在使用sprintf,我确信这是一种糟糕的做法。

编辑:如果我通过了哈希包围的日期,那么我仍然会得到如下错误:

致命错误:未捕获异常"PDOException",消息为'SQLSTATE[2218]:强制转换规范的字符值无效:-3030[Microsoft][ODBC Microsoft Access Driver]条件表达式中的数据类型不匹配。(SQLExecute[-3030]位于ext''pdo_odbc''odbc_stmt.c:254)'中C: ''examplep''htdocs''ips''php''classes.php:49堆栈跟踪:#0C: ''examplep''htdocs''ips''php''classes.php(49):PDOStatement->execute()#1C: ''examplep''htdocs''ips''php''classes.php(52):数据库->execute()#2C: ''examplep''htdocs''ips''try2.php(12):数据库->结果集()#3{main}在第49行的C:''examplep''htdocs''ips''php''classes.php中抛出

通常,当使用准备好的语句或参数化查询时,您不需要担心分隔字符串和日期值;所有这些都是在"幕后"为您处理的。

我只是尝试了以下方法,它对我有效:

<?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);
}

您应该将日期(整个值)放入bindValue方法中。示例:

$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