Possible Duplicate:
Best way to stop SQL Injection in PHP
I need to secure this code from SQL injection attacks, possibly using mysql_real_escape_string
. Where and how do I apply it?
<?php
mysql_select_db("database");
$sql="INSERT INTO email (address) VALUES ('$_POST[address]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<center>THANK YOU!</center>";
?>
You should be able to just wrap your post value in mysql_real_escape_string():
$address = mysql_real_escape_string($_POST[address]);
$sql="INSERT INTO email (address) VALUES ('$address')";
Stack Overflow is less for teaching and more for authoritative answers to less-common questions.
What you've got is a common question, "how do I use this function," and it's much better to use the PHP docs to answer that sort of thing. So for example, you look up mysql_real_escape_string
in the documentation and you find this page: http://php.net/manual/en/function.mysql-real-escape-string.php
Which has example code like:
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>
Adapting this into your case would give:
$sql = sprintf("INSERT INTO email (address) VALUES ('%s')",
mysql_real_escape_string($_POST['address']));
Or you could do it in two phases,
$email = mysql_real_escape_string($_POST['address'])
$sql = sprintf("INSERT INTO email (address) VALUES ('$email')"