-4

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>";

?> 
Community
  • 1
  • 1
user977101
  • 161
  • 2
  • 12

2 Answers2

2

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')";
BluesRockAddict
  • 15,525
  • 3
  • 37
  • 35
1

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')"
CR Drost
  • 9,637
  • 1
  • 25
  • 36
  • I'm not sure I follow. Are we to adapt the authoritative answers to each case of a questioner that doesn't search for and find and apply such answers on their own? – dldnh Mar 31 '12 at 21:39
  • Oh, "authoritative answers"? "Less common questions"? You are apparently mixed Stackoverflow with some other site. :) Anyway, sprintf looks useless in the last line, while die() in the first one is plainly wrong. – Your Common Sense Apr 01 '12 at 06:27