Skip to content Skip to sidebar Skip to footer

PHP prevent SQL Injections

Reading Time: 2 minutes

How to access disable or prevent sql injections using php.This is a most important topic when you are creating a web site or web applications.So in this articles is describing how to prevent sql injections using php.

What is the SQL Injection?

SQL injection is a form of attack on database-driven web site or web application. An attacker executes unauthorized SQL commands by taking advantage of insecure code/script/commands on system connected to the Internet.

The goal of SQL Injection?

SQL injection attacks are used to steal information(specially database connection information) from a database from which the data would normally not be available and/or to gain access to an organization’s host computers through the computer that is hosting the database.

How to prevent SQL Injection?

Following function can be use to prevent many of the sql injection attack by using url.

function cleanURLData($field) {
	if (get_magic_quotes_gpc()) {
	 $field = stripslashes($field);
	$field = mysql_real_escape_string($field);

How to use this.

$userID = $_GET['userID']; // get url data
$userID = cleanURLData($userID); //pass to the function

Think this is my url.
Consider above url, if attacker is sending userID=3′ (note the single quote here at last), your sql query doesn’t execute.That may be display an error.So attacker can get tables data by viewing error message.So if you call to above function, that adding slashes and after remove it and so on.Then if coming url with unwanted characters definitely sql query will be execute.
If you want to remove unwanted characters from url string view my another article named “PHP remove special characters in the string”
If user send userID=“5; DELETE FROM users”; like this.You can do the following method to execute the sql statement.

$userID = “5; DELETE FROM users”;
$userID = (int)$userID ; // 123
mysql_query( $connection, “SELECT * FROM users WHERE id={$id}” ); // this is safe

Also you can test above functions by passing parameters in the url.
If coming url parameters with spaces,you can use php trim() function to remove white spaces.

// url  = 3 & useremail=eee@[email protected]
$userID = $_GET['userID '];
$userID = trim($userID) ; // remove white spaces