Changing Database Entries on the Fly by Embedding PHP Variables

When pulling information from a database, have you ever needed to change aspects of the text on the fly? For example, I have a form that contains several questions like "Did you utilize any of the website resources in 2011?" These questions are stored in a database and need to change annually. So next year the 2011 should be changed to 2012. The year could be removed altogether in some cases, but others require the year to remain. In a perfect world, a PHP variable could be stored in the database along with the question, but that can't be done…can it?


If we could utilize PHP variables, the database entry for the question mentioned earlier would look something like this:

Did you utilize any of the website resources in $survey_year?

If the question was displayed as is, PHP wouldn't see the variable. The question would appear exactly how it's written in the database.


With a little manual intervention, however, the variable name could be used as a placeholder. We just need replace all occurrences of the string "$survey_year" with a real PHP variable by using str_replace().

$survey_year = '2011';
$current_question = 'Did you utilize any of the website resources in $survey_year?';
$current_question = str_replace('$survey_year', $survey_year, $current_question);

Note: the first argument of str_rplace() is enclosed with single quotes to prevent PHP from interpreting the variable before the string replacement happens.


There are currently no comments.

Leave a Comment