hon
hon

Reputation: 135

pass variable into php eval()

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

Answers (5)

ReflectYourCharacter
ReflectYourCharacter

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

WonderLand
WonderLand

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

chombe
chombe

Reputation: 65

You are missing a semicolon. Try this:

eval("\$str = \"$str\";");

Upvotes: 2

oezi
oezi

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

Daren Thomas
Daren Thomas

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

Related Questions