WebRef.eu  - Internet Marketing and Online Business Resources  

Home / Site Map | Blog | TwitterTwitter | Contact

Back to PHP Scripts List

PHP Script to Sanitise Form Input for a MySQL Database

The following function can be used to remove potentially dangerous characters from a form input field before the data is inserted into a MySQL database:

function makeSQLSafe($str)
{
// check the status of magic_quotes_gpc, if it returns true
// we remove the escaped characters. Allowing for the real escaping
// to be done via mysql_real_escape_string
if(get_magic_quotes_gpc())
{
// remove the slashes.
$str = stripslashes($str);
}

$str = mysql_real_escape_string($str);

return $str;
}
//End of function

Here's an example of how the function would be used in practice. We would obtain the form input in the normal way, e.g. as follows:

$ReviewDesc=$_POST['txtReviewDesc'];

Then when the various field values are input into the database, we cleanse them by calling the makeSQLSafe function on them as follows:

//database query
$query = "INSERT INTO Reviews (ProductId, ReviewRating, ReviewDesc, ReviewDate, ReviewIsApproved) VALUES ('" .
makeSQLSafe($ProductId) . "', '" .
makeSQLSafe($ReviewRating) . "', '" .
makeSQLSafe($ReviewDesc) . "', '" .
makeSQLSafe($DateAndTime) . "', '" .
makeSQLSafe(0) . "')";

 

Back to PHP Scripts List

 




Low Prices UK Shopping

Compare Prices
at LowPrices.co.uk


Home / Site Map | TwitterTwitter | Contact

All Content ©2018 WebRef.eu