It is relatively easy to protect against a SQL Injection attack on a web application with a database. The best way is to ensure that all numeric type variables used in a Query are in fact numbers, before running the query. It is good that you are concerned about SQL injection as some serious and large scale thefts of credit card information have been commited using the SQL Injection attack on the internet.
Usually a web page is vulnerable to SQL Injection if it has the following format, with a URL numeric variable is not properly validated to be a number, often URL variables are used in web applications. Like the following URL:
The URL variable 999 is the primary key ID of a database table and is an integer type. This is often used in web applications on the internet, including web apps made with ASP .NET and ColdFusion. The problem occurs when a query like the following, in our example file RegisterUser.php, uses the UserID passed into the page as URL variable.
$dbquery = "SELECT * FROM tblUser WHERE UserID = " . $_GET['UserID'];
In this instance with the URL above, the query would evaluate to the following string:
SELECT * FROM tblUser WHERE UserID = 999
However, the risk for SQL Injection comes from the URL variable UserID, a malicious user could make the URL variable equal to an arbirtrary SQL command like the following:
WHen this is evaluated by the PHP code, it will turn into the following string:
SELECT * FROM tblUser WHERE UserID = 0;Drop Table tblUser;
This is a valid SQL statement and will be executed by the database, as you can see, in this manner the maliscious user can add arbitrary SQL statements to a web page and have those statements executed by the DB. Even worse, if the DB query results are dynamically displayed on the webpage, the malicious user can also see all the results of the Querys they are adding to the page. In effect, the malicious user is granted total control of the database in this manner.
This kind of attack was has been used by criminals to steal credit card numbers from web exposed Databases, especially DBs that are used in web based credit card transactions.
The kind of SQL injection described herein usually only works with Numeric database column types, for string types there is not much risk because the data passed into the URL variable will be enclosed within quote marks within the SQL Query, so any SQL command inside the quotes will not be executed by the DB.
The best way to protect against SQL injection is to make sure all numeric value variables that are to be used in a SQL Query are validated to make sure they are only numbers. There are many different ways to do this in PHP.
Hope this helps, also SQL injection can be used in web forms where a numeric type in the form is not properly validated to ensure it is a number.
Michael G. Workman