php code into variable

0 votes
asked Jun 25, 2016 by the-boy-za

I want to insert a PHP code into a variable.

I want to replace "Some text" with a PHP code.

I found some examples on the internet, but when I try to run my script it isn't working.

This is my current script:$purchaseID = "Some text";

I want to change "Some text" with the following code:

<?php echo date('y/m/d'); echo "O"; $link = mysql_connect("localhost", "root", ""); mysql_select_db("db", $link); $result = mysql_query("SELECT * FROM table", $link); $num_rows = mysql_num_rows($result);echo "$num_rows"+1;
?>

I have tried:

$purchaseID = <<<END
echo date('y/m/d');
echo "O";
$link = mysql_connect("localhost", "root", "");
mysql_select_db("db", $link);
$result = mysql_query("SELECT * FROM table", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows"+1;
END;

When I run this I get a error.

How can I fix this and replace "Some text" with the PHP code?

4 Answers

0 votes
answered Jun 25, 2016 by olibiaz

If i understand well your need, you just need to concatenate the different part of the string:

$purchaseID = date('y/m/d');
$purchaseID .= "O";
$link = mysql_connect("localhost", "root", "");
mysql_select_db("db", $link);
$result = mysql_query("SELECT * FROM table", $link);
$num_rows = mysql_num_rows($result);
$purchaseID .= $num_rows + 1;

You will get (considering $num_rows to be 4)

2016/06/24O5

Do you really need the heredoc syntax here?

0 votes
answered Jun 25, 2016 by quasimodos-clone

You are using the heredoc syntax, that interpolates variables. You might want the herenow syntax without interpolation:

$purchaseID = <<<'END' echo $variable;
END;
// $purchaseID == "echo $variable;"

Enclose the delimiter into single qoutes. Interpolation is not done in this case. To execute the code, you have to use eval($purchaseID);. Be aware, that eval has a dangerous potential when relying on external data.

0 votes
answered Jun 25, 2016 by jyothi

try but i don't recommend you eval

There are some side effects using eval() refer and learn here

<?php
$time = '<?php echo time(); ?>';
eval('?>'.$time.'<?php;');
?>
0 votes
answered Nov 8 by ikari

You would have to escape the variables, like this:

$purchaseID = <<<END
echo date('y/m/d');
echo "O";
\$link = mysql_connect("localhost", "root", "");
mysql_select_db("db", \$link);
\$result = mysql_query("SELECT * FROM table", \$link);
\$num_rows = mysql_num_rows(\$result);
echo "\$num_rows"+1;
END;

That's it!

Cheers!

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...