我需要执行以下查询
switch($interval) {
case "1 month":
$interval = "1 month";
break:
case "1 year":
$interval = "1 year";
break:
}
db_query("SELECT fid FROM file_managed WHERE FROM_UNIXTIME(TIMESTAMP) <= DATE_SUB(NOW(), INTERVAL :interval)", array(":interval" => $interval))
此查询引发sql错误,因为您可以看到“1个月”附近添加单引号
已执行的查询 SELECT fid FROM file_managed WHERE FROM_UNIXTIME(TIMESTAMP)&lt; = DATE_SUB(NOW(),INTERVAL'1 month')
预期查询: SELECT fid FROM file_managed WHERE FROM_UNIXTIME(TIMESTAMP)&lt; = DATE_SUB(NOW(),INTERVAL 1个月)
关于如何摆脱单引号的任何想法?
答案 0 :(得分:0)
如果你有$ interval变量的可信参数值(例如,它不是来自用户,而是填充它),你可以将它放在sql字符串中而不是绑定它,如下所示:
$interval = "1 year";
db_query("SELECT fid FROM file_managed WHERE FROM_UNIXTIME(TIMESTAMP) <= DATE_SUB(NOW(), INTERVAL {$interval})");
它将运行下一个sql查询:
string(95) "SELECT fid FROM file_managed WHERE FROM_UNIXTIME(TIMESTAMP) <= DATE_SUB(NOW(), INTERVAL 1 year)"
(使用双引号代替单个sql字符串,让PHP解释器评估嵌套变量)