Jump to content

[SOLVED] Reassign value to variable in a foreach loop


techtheatre

Recommended Posts

This specific example is for stripping "bad stuff" out of posted text in a form.  i know there are countless other ways to do this, and that the topic has been covered elsewhere on these message boards, but the method i wanted to use below brought a puzzling problem to my mind.  The question below has more to do with how to get the value stored int eh variable name than the actual effictiveness of the script.

 

I am posting a variety of values from a form into a script.  Before plugging this into my MySQL database, i want to clean out any bad characters.  I have written a foreach loop to go through each of the posted (in this case i am actually using $_REQUEST) variables.  Ideally at the end i want to have a list of the variables with the "clean" value assigned to them.

 

for example, this string:

insert.php?name=bob&age=25&gender=male

 

will be read in as $_REQUEST['name'] == "bob"

and after my foreach loop, i want there to be a variable declared called $name with the stored value of "bob"

 

 

//strip bad stuff from posted variables
foreach( $_REQUEST as $VariableName => $VariableValue){
$VariableValue = stripslashes(trim($VariableValue)); //strip slashes and clean up trailing whitespace
$VariableValue = htmlentities($VariableValue, ENT_NOQUOTES);  //strip special characters
$VariableValue = nl2br($VariableValue);	// replace "new line" characters with <br />
$VariableValue = addslashes($VariableValue);	// escape quote marks

$VariableName = $VariableValue;  //this is the "problematic" line
}

 

in the last line above, i know that it does me no good to assign the "clean" value stored in $VariableValue as the value of an unused variable named VariableName...i want to store the value in a variable named whatever the stored value of $VariableName is...

 

aarg...so confusing...i am sure there is a simple answer out there, and any help is greatly appreciated.  Thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.