Feb 17, 2010 06:45 PM
(This post was last modified: Apr 6, 2011 06:06 PM by ChineseFountain.)
How to protect your forms from SQL injection!
We all know it's fun to hack and deface websites. But how would you feel if it happened to you? So, here is an easy tutorial to prevent your website from being SQLi'd.
Here is the code for a vulnerable form:
PHP Code
<?php
include "conn.php"; //connect to database
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysql_query($sql);
echo "User registered";
?>Anyone could inject that.
But, we can make a simple adjustment to fix that up! Use this code instead!
PHP Code
<?php
include "conn.php"; //connect to database
$username = $_POST['username'];
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
$password = mysql_real_escape_string($password);
$password = md5($password);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysql_query($sql);
echo "User registered";
?>As you can see, I've added the function mysql_real_escape_string(); to the $username and $password variables. It's that simple! I've also md5'd the password, since it was all lonely and unencrypted out there. :D That was for an example, I recommend using a salt so you can't just take that hash to a decoder and decode the md5.
Thanks for reading this fairly short tutorial!
![[Image: JcVeD.png]](https://i.imgur.com/JcVeD.png)
“Be Who You Are and Say What You Feel Because Those Who Mind Don't Matter and Those Who Matter Don't Mind.” - Dr. Seuss


