Reputation: 28354
I have the following in database field
id = id,
Xterminal = 1234,
Testdata = 1234',
date BETWEEN $Date1 AND $Date2,
MyVar = $myVar;
I want to use it in my sql statement. I have $Date1 = '2011-01-09' and $Date2 = '2011-03-09' set in my scripte above the sql statement. I have $myvar setup to $myVar = 3. But it doesnt convert the variables in sql and when I do print_r on $sql it shows the variables and even in query it shows variables not the values of them
I doing the following
$conditions = explode(',',$results['conditions']);
print_r($condidtions) gives
Array ( [0] => id = id [1] => Xterminal = 1234 [2] => Testdata = 1234 [3] => date BETWEEN $Date1 AND $Date2 [3] => MyVar = $myVar;
)
$sql1 = "Select * from table where ";
$sql2 = implode(' AND ',$conditions);
$sql = $Sql1.' '.$sql2;
print_r("$sql") gives
SELECT * FROM
table WHERE id = id AND Xterminal = 1234 AND Testdata = 1234 AND date BETWEEN $Date1 AND $Date2 AND MyVar = $myVar;
Not sure why is it not taking my variable values that I have defined alreadt at the to of script
Upvotes: 0
Views: 61
Reputation: 38526
It sounds like what you're saying is that the string date BETWEEN $Date1 AND $Date2,
came from the database. If that is the case, then your variables are not being evaluated, because this is just data...
You can use eval(), but this is a dangerous path if users could possibly create these conditions.
$conditions = explode(',',$results['conditions']);
for ($x = 0; $x < count($conditions); $x++) {
eval("\$conditions[\$x] = \"" . $conditions[$x] . "\";");
}
print_r($conditions);
Edit: I put together a working PHP sample for this, visible at http://gfosco.kodingen.com/conditions.php and here is the source:
<?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);
This outputs:
$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'," }
Upvotes: 1
Reputation: 9148
Maybe try this:
date BETWEEN {$Date1} AND {$Date2},
No sure it will work since I can't see the way your variables are set in your script.
Upvotes: 0