Preventing SQL Injection with PHP and MySQL

Posted: May 2, 2011 in Technical

SQL injection is a huge issue. Make sure you protect your sites. It’s easiest to do when first building a project, because other items in your code can affect this method. If you use addslashes() anywhere before inserting a value from form data into the DB, then you will want to stop using that function. This function will also handle html forms that pass data in POST as arrays. For example:

<form method="post">
<input type="text" name="values[0]">
<input type="text" name="values[1]">

In PHP, that comes out as


Using the mysql_real_escape_string() function that is built into PHP, it’s relatively easy to prepare a single value for entry into a SQL DB. This method makes it easy to process ANY 2 level array (i.e. a POST or GET array with arrays in it). Passing arrays one level deep, will work with this method. It’s easy to add on another level, as you can see:

Use this function:

function procformdata($var)
		foreach($var as $i => $val)
			if (is_array($val))
				foreach($val as $i2 => $val2)
					$val[$i2] = mysql_real_escape_string($val2);
				$var[$i] = $val;
				$var[$i] = mysql_real_escape_string($val);
		return $var;

Then use these lines of code, to check your POST and GET data:

$_POST = procformdata($_POST);
$_GET = procformdata($_GET);

Note that once you have run these methods, the data is ready for insert into a mysql database. If you want to display any of this data, certain characters will be escaped, so you may want to run removeslashes() on the data to display it after being processed by this function.

  1. syrian says:

    what kind of fucking explanation is this shit ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s