Reputation: 135
I am using php eval() function, below are my statements:
$uid = 8;
$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid';
eval("\$str = \"$str\"");
die("$str");
//$query = $_SGLOBAL['db']->query($str);
//$result = $_SGLOBAL['db']->fetch_array($query);
The output is: SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid That's to say the varibale $uid did not passed. How to pass a variable into the evaluated string. Thanks.
Upvotes: 6
Views: 6906
Reputation: 972
You can use this too, but it makes no sense and it's the wrong logic for using eval
Example 1:
<?php
$uid = 8;
$OUTPUT = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';
eval(" ?> $OUTPUT <?php ");
echo $str;
exit;
?>
Example 2:
<?php
$uid = 8;
$str = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';
eval(" ?> $str <?php ");
echo $str;
exit;
?>
Upvotes: 1
Reputation: 5674
According to php manual: http://php.net/manual/en/function.eval.php
The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.
So, if the variable you need is defined in the scope where you calleval()
, everything should work as expected.
Upvotes: 4
Reputation: 51817
you can't insert varuiable into single-quotet strings directly. try this:
$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; // double-quotet
or this:
$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid='.$uid; // string-concatenation
Upvotes: 3
Reputation: 70354
Variable substitution only works in double quoted strings.
Try this:
$uid = 8;
$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; # variable gets substituted here
eval("\$str = \"$str\"");
die("$str");
I think variable substitution is something that happens at parse time - it is not done recursively, so in your eval
, the contents of $str
is pasted into the string, but that isn't done a second time for the contents of $uid
inside $str
.
Upvotes: 1