变量值缺失

时间:2011-06-07 18:27:52

标签: php cakephp-1.3

我在数据库字段中有以下内容

id = id,
Xterminal = 1234,
Testdata = 1234',
date BETWEEN $Date1 AND  $Date2,
MyVar = $myVar;

我想在我的sql语句中使用它。我在sql语句上方的脚本中设置了$ Date1 ='2011-01-09'和$ Date2 ='2011-03-09'。 我将$ myvar设置为$ myVar = 3.但它不会转换sql中的变量,当我在$ sql上执行print_r时它会显示变量,甚至在查询中它显示变量而不是它们的值

我做了以下

$conditions = explode(',',$results['conditions']);   

print_r($ condidtions)给出了

阵 (     [0] => id = id     [1] => Xterminal = 1234     [2] => Testdata = 1234     [3] => 日期BETWEEN $ Date1和$ Date2     [3] => MyVar = $ myVar;

$sql1 = "Select * from table where ";
$sql2 = implode(' AND ',$conditions);

$sql = $Sql1.' '.$sql2;

print_r(“$ sql”)给出

选择     * FROM

表 哪里 id = id AND Xterminal = 1234 AND Testdata = 1234 AND 日期在$ Date1和$ Date2 AND之间 MyVar = $ myVar;

不确定为什么不采用我在脚本

中定义了alreadt的变量值

2 个答案:

答案 0 :(得分:1)

听起来你说的是字符串date BETWEEN $Date1 AND $Date2,来自数据库。如果是这种情况,那么您的变量不会被评估,因为这只是数据......

您可以使用eval(),但如果用户可能创建这些条件,则这是一条危险的路径。

$conditions = explode(',',$results['conditions']);
for ($x = 0; $x < count($conditions); $x++) {
    eval("\$conditions[\$x] = \"" . $conditions[$x] . "\";");
}
print_r($conditions);

编辑:我为此汇总了一个可用的PHP示例,在http://gfosco.kodingen.com/conditions.php处可见,这是源代码:

<?php

$conditions = array("date BETWEEN '\$Date1' AND '\$Date2',");

echo "\$conditions before the loop: <BR>";
var_dump($conditions);

$Date1 = '1/1/2011';
$Date2 = '12/31/2011';

echo "<BR>\$Date1 = " . $Date1 . "<BR>";
echo "\$Date2 = " . $Date2 . "<BR>";

for ($x = 0; $x < count($conditions); $x++) {
    eval("\$conditions[\$x] = \"" . $conditions[$x] . "\";");
}

echo "<BR>\$conditions after the loop:<BR>";
var_dump($conditions);

输出:

$conditions before the loop: 
array(1) { [0]=> string(35) "date BETWEEN '$Date1' AND '$Date2'," } 
$Date1 = 1/1/2011
$Date2 = 12/31/2011

$conditions after the loop:
array(1) { [0]=> string(41) "date BETWEEN '1/1/2011' AND '12/31/2011'," }

答案 1 :(得分:0)

也许试试这个:

date BETWEEN {$Date1} AND  {$Date2},

不确定它是否会起作用,因为我无法看到您的脚本中设置变量的方式。