Skip to content

Evaluate PHP Variables in MySQL

If the data retrieved from MySQL contains PHP variables, how to properly evaluate the variables into values? Here is an example to play the magic.

First of all, let's see what the data we have in the example:

mysql> select name, introduction from table_name where id = 1;
+---------+-----------------------+
| name    | introduction          |
+---------+-----------------------+
| Foo Bar | Hi, my name is $name. |
+---------+-----------------------+
1 row in set (0.00 sec)

You can notice that we have a PHP variable $name in the column introduction, which should be translated to a normal string by PHP. Now, we would like to use the value of the column name to substitute $name.

Here's the code:

1  <?php
2  $dbh = new PDO(...);
3  $result = $dbh -> query("select * from table_name where id = 1") -> fetch();
4  $name = $result['name'];
5  eval("$introduction = "" . $result['introduction'] . "";");
6  echo $introduction;
7  ?>

In the line 4, we assign the value from the first column to $name, and the very key step is in the line 5, we use function eval() to evaluate the string as codes, which will turn $name into "Foo Bar", then we output the result in the line 6.

The output is:

Hi, my name is Foo Bar.

Yes, this is what we want. Actually, we can combine the last two lines into a single line:

5  eval("echo "" . $result['introduction'] . "";");

Leave a Reply

Your email address will not be published. Required fields are marked *