Reputation: 1561
I am new to sql how do i make this code more secure from sql injection and over wrong doing.
// Variables
$db_host = 'localhost';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'db';
$Username = $_POST['username'];
$Email = $_POST['email'];
// DB Connect
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
$connection = $connect;
mysql_select_db( $db_name, $connect ) or die( mysql_error() );
// Inserting into DB
$qInsertUser = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`) VALUES ( ``, `$Username`, `$Email`) ");
if ($qInsertUser){
echo "You are now subscribed to our newsletter. Thank you!";
} else {
echo "Error!";
}
Upvotes: 0
Views: 59
Reputation: 2294
Beside mysql_real_escape_string, also try to validate the input. users shouldn't be allowed to enter whatever. use regexp syntax and type casting or settype. this I mean on server side in php. javascript validations are not enough I've seen many programmers and webmasters spend more energy on js validation while in php they write no validation at all.
Upvotes: 0
Reputation: 104080
You should probably use prepared statements. Instead of:
$qInsertUser = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`) VALUES ( ``, `$Username`, `$Email`) ");
Replace it with a prepared statement and execution:
$sth = $dbh->prepare('INSERT INTO `database` (`id`, `username`, `email`) VALUES (?, ?, ?)');
$sth->execute(array($id, $username, $email));
Let the libraries handle all the quoting for you.
Upvotes: 1
Reputation: 8344
Make sure you are escaping the values. Rather than:
$Username = $_POST['username'];
$Email = $_POST['email'];
try this:
$Username = mysql_real_escape_string($_POST['username']);
$Email = mysql_real_escape_string($_POST['email']);
Please note that this answer is by no means meant to be an exhaustive anti-SQL-injection resource, but hopefully it will get you going on the right track.
Upvotes: 0