unloco
unloco

Reputation: 7320

PHP: evaluate values inside string

I have this string ($query) returning from preg_replace

'SELECT ({$array["sum"]}/ 5)'

how can i evaluate it, so that the result would be 'SELECT (100/5)' for example !

I tried

eval($query)

But with no success!

Do you have a better idea ?

Upvotes: 0

Views: 114

Answers (3)

hakre
hakre

Reputation: 197767

you're not using eval right:

$evaluated = eval("return $query;");

take care you do not have any syntax errors. also you just might do it wrong when you build SQL queries this way. Just saying, I hope you're old enough.

Upvotes: 1

JvdBerg
JvdBerg

Reputation: 21856

Just glue them together with the . operator:

$array['sum'] = 100;
echo 'SELECT (' . $array['sum' ] . ' / 5)';

will result in:

SELECT (100 / 5)

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Just replace the single quotes ' with double quotes ".

"SELECT ({$array["sum"]}/ 5)"

And it is not a good idea to use eval() during $_POST or while getting input from users. Just a suggestion.

Upvotes: 1

Related Questions