好吧,首先,我对如何使用php知之甚少,对sql只有稍微了解一点。所以,如果我做的任何事情看起来真的,真的很愚蠢,请原谅我。
给定用户输入的日期、时间和时间间隔,我需要获得两个不带时区的时间戳——一个开始时间和一个结束时间。例如
function myfunction($startdate, $starttime, $numhours){
$start = $startdate.' '.$starttime;
//I know this works for a timestamp because I have used this value in other sql statements and have been returned the correct results
$handler = $connection->prepare("SELECT TIMESTAMP :start + INTERVAL :numhours ' HOURS'");
$handler->bindParam(':start', $start);
$handler->bindParam(':numhours', $numhours);
$handler->execute();
$end = $handler->fetchAll();
这只会给我以下错误:
Submitting booking.SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1" LINE 1: SELECT TIMESTAMP $1 + INTERVAL $2 ' HOURS'
我还没能找到任何真正告诉我我在这里做错了什么(这可能是很多)。谢谢你的帮助。
编辑:我使用postgreSQL
,通过' pgAdmin III
编辑:$start的格式应该是'YYYY-MM-DD HH:MM:SS'
问题是,您使用带有值(参数)的文字表示法,而不是带有常量的文字表示法。
文字表示法只接受以下内容:
SELECT TIMESTAMP '2014-05-25 14:29:59' + INTERVAL 3 HOUR;
不能接受常量以外的值(表达式)(绑定的参数也不是常量):
-- this will throw a syntax error
SELECT TIMESTAMP CONCAT('2014-05-25', ' ', '14:29:59');
您可以在这里使用CAST
形式的文字表示法:
$handler = $connection->prepare('SELECT CAST(:start AS TIMESTAMP) + ' .
'CAST(:numhours || '' hours'' AS INTERVAL)');
$handler->bindParam(':start', $start);
$handler->bindParam(':numhours', $numhours);
$handler->execute();
EDIT:或者,你可以使用PDO::ATTR_EMULATE_PREPARES
在你的查询中使用真实的文字,但我相信postgres自己的准备功能是更好的选择。