4

Possible Duplicate:
Best way to prevent SQL Injection in PHP

Is this code protected enough against sql injection

if(isset($_POST['Submit']))
{
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
$confirm_key=md5(uniqid(rand()));

$query = mysql_query("INSERT INTO members 
(user, pass, mail, confirm_key, country, city, www, credo)
VALUES  ('$user','$pass','$_POST[mail]','$confirm_key','$_POST[country]','$_POST[city]','$_POST[www]','$_POST[credo]')")
or die ("Error during INSERT INTO members:    " . mysql_error());
exit();
}

Is this the right way and must be each input (like country, city...) be protected ?

Community
  • 1
  • 1
Alegro
  • 7,534
  • 17
  • 53
  • 74

2 Answers2

5

DO NOT USE mysql_query for new applications. You should be using mysqli or PDO to do your escaping with placeholders. There are many examples you can use.

Generally your SQL should look like:

INSERT INTO `table` (column) VALUES (?)

It SHOULD NOT look like:

INSERT INTO `table` (column) VALUES('$dangerous_user_content')

If you use placeholders properly it's almost impossible to create a SQL injection hole.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Hm, ok, I will tray. Thanks for explanation. – Alegro Aug 02 '12 at 21:00
  • You can see in your example how tricky and dangerous `mysql_query` is. You escaped `$user` and `$pass` but completely forgot about `$_POST[country]`. Spend the short amount of time to do it right and you'll be safe and secure. Always test your application with a variety of input, especially including both `'` and `"`. – tadman Aug 03 '12 at 00:42
1

http://php.net/manual/en/function.mysql-real-escape-string.php

Even the php docs say don't use mysql_real_escape_string

rk2z
  • 58
  • 3