PHP tricks, #1 – eval()

17 January 2006, 13:55 CST

Found a new “trick” in PHP today, so I thought I’d share this one and a couple of others I’ve picked up over the last couple of months. In all likelyhood, these are not specific to PHP but rather constructs that are present in other languages as well.

1. Using PHP variables in mySQL
Not in the SQL itself, but suppose you want PHP to evaulate a variable stored in a mySQL field result? For example, you need to display a URL but need to change it depending on the page it is displayed on, you can put a variable in the data that is stored in the database, like so:

http://www.mywebsite.com/page.html?color=$color

PHP does not parse “$color” but rather just dumps that string out like it is. In my case, I needed to create a link to a specific spreadsheet, based on the page I was on*. However, the link to the spreadsheet is stored in the DB. Solution? Use the eval() function, like so

eval("\$new_url = \"$stored_url\";");

So if the variable color is “red” you end up with

http://www.mywebsite.com/page.html?color=red

More info on eval is here: http://us3.php.net/eval

(I don’t really understand why it looks like that and why you have to escape the first $ but not the second, but it seems to work.)

* More specifically, I have metadata for a series of pages stored in the database. Each page pulls not only its own metadata, but also data for a specific geography based on a script variable. I needed the URL stored in the metadata to follow the geographic ID in order to retrieve the proper file.

Leave a Reply