so I had a friend of mine try to run a SQLinjection on my site and he managed to get into it using the code underneath. How can I prevent this? I have read something about s
The idea of prepared statements is that you don't concatenate variables, instead you bind the parameters. The difference is the variable never gets inserted into the SQL, rather the MySQL engine handles the variable separately which leaves no possibility of SQL Injection. This also has the added bonus that no escaping or pre-processing of the variable is required.
$query = $db->prepare("SELECT password FROM login WHERE username = :username");
$query->execute(array(':username' => $username));
Prepare your statement like this:
$query = $db->prepare("SELECT `password` FROM `login` WHERE `username` = :username");
$query->execute(array(":username" => $username));
Or bind the parameters using the same prepared statement like this:
$query->bindParam(":username", $username, PDO::PARAM_STR);
$query->execute();
This way you shouldn't have to sanitize your query.
Don't sanitize input. Just make sure that you really write to the database what ever data is provided (i.e. protect against SQL injection) and then escape your output.
To protect against SQL injection, use bound parameters. To escape your output, use htmlspecialchars on web pages and any other encoding appropriate given the medium you are outputting to.
Just remember that you have to do both of the above. If you only protect against SQL injection attacks, you'll still leave your site wide open to XSS attacks.