SQL Query不接受所有参数的变量

时间:2013-02-26 10:59:12

标签: sql

我有一个带有event_id列和scheduled_at列的数据库表。 该查询在php中调用,如下:

$columnName = 'scheduled_at';
$start = '2013-02-26';
$end = '2013-02-27';
// query to be executed
$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $end );

执行时查询不起作用,但以下操作

$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND '2013-02-27' );

$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN $start AND $start );

不起作用,但以下工作

$sql = ( SELECT * FROM $table WHERE $columnName BETWEEN '2013-02-27' AND '2013-02-27' );

手动插入值会使其工作,但会失去函数的实用性。任何想法为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

您需要引用变量,以便创建的SQL字符串包含日期值周围的引号。例如

$sql = "( SELECT * FROM $table WHERE $columnName BETWEEN '$start' AND '$end' )";