Quick and easy $_POST security…
Oct 25th, 2007 by Steven Lloyd Watkin
A quick and easy way to protect yourself from mySQL injection attacks in PHP is to use…
$sql = "insert into table set ";
foreach ($_POST as $key => $data)
{
$sql .= $key." = '".strip_tags(htmlentities(addslashes($data)))."',";
}
$sql .= mysql_query(rtrim($sql,',').";") or die(mysql_error());
What this script does is to take your $_POST data and remove anything malicious from it. Looping over the $_POST data we build up an SQL statement. At the end then we simply execute using with mysql_query.
NOTE: This does not validate your data, it just helps prevent malicious attacks.
Another version of this that I use to to grab all my form information into variables to to place the following code within the foreach loop instead…
eval("$".$key." = '".strip_tags(htmlentities(addslashes($data)))."';");
This makes up a list of variables following your forms field names and strips malicious code from them. This method then allows you to do some form validation before inserting data into your tables 





