Possible Duplicate:
Best way to stop SQL Injection in PHP
I just got this PHP script to post my form fields to a SQL table, and it's working fine. Since I plan on using this site with many users, I do not want to allow SQL-Injection's to ruin everything. I am a huge noob to PHP and I was hoping someone here could help me SQL-Inject proof my code.
<?php
//Check for mysql connection
if (!mysql_connect("mysql4.000webhost.com","a3516066_form","lasvegas1"))
die('Could not connect: ' . mysql_error());
//Escape SQL characters to protect against SQL injection
$username = mysql_real_escape_string($_POST['username']);
$hostname = mysql_real_escape_string($_POST['hostname']);
$ip = mysql_real_escape_string($_POST['ip']);
$email = mysql_real_escape_string($_POST['email']);
mysql_select_db("a3516066_form");
//Query to check for username match
$userCheck = "SELECT * FROM `Accounts` WHERE username = '$username'";
if(mysql_num_rows(mysql_query($userCheck)) != 0)
die("Sorry, username is already in use. Please go back and try again.");
//If the username isn't found, insert the values
$sql = "INSERT INTO Accounts VALUES ('$username','$hostname','$ip','$email')";
if (mysql_query($sql)) {
//Successful query
header ("location: /done.html");
exit();
} else
//Failed query
die("Something is wrong, we could not complete your request.");
?>