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, let's say you have a form which is populated from a database with questions like "Did you utilize any of the website resources in 2011?" If the form is submitted annually, the 2011 needs to correspond with the year the form is being filled out by visitors. You could remove the year, but what if the question becomes too vague without it. In a perfect world, we could store a PHP variable in the database along with the question, but we can't do that…can we?
If we could utilize PHP variables, our database entry for the question mentioned earlier would be modified to something like this:
Of course if we displayed the question as is, PHP wouldn't know about the variable. Instead it displays the text exactly as it appears in the database. But with a little manual intervention, we can use the variable as a placeholder. We just need replace all occurrences of the $survey_year with the true value using the str_replace() function.
$current_question = 'Did you utilize any of the website resources in $survey_year?';
$current_question = str_replace('$survey_year', $survey_year, $current_question);
Note that the first argument of str_rplace() is enclosed in single quotes which prevents PHP from interpreting the variable before the string replacement happens.
0 Comments
There are currently no comments.
Leave a Comment