1

The code below is written in php:

$user = addslashes($_POST['user']);
$pwd = addslashes($_POST['pwd']);

$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";

the query will then be sent to mysql Is there anything more I need to take care of?

Please point out.

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
NSF
  • 2,499
  • 6
  • 31
  • 55
  • possible duplicate of [Best way to prevent SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) – Code Magician Jun 17 '12 at 17:25

4 Answers4

6

No it's not safe, use mysql_real_escape_string at minimum:

$user = mysql_real_escape_string($_POST['user']);
$pwd = mysql_real_escape_string($_POST['pwd']);

And for better security go for prepared statements.

Best Options:

You may ask which one to choose, check out:

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
5

Nope.

The reason is that while a single quote ' is not the only char that break a sql query, quotes are the only chars escaped by addslashes().

Better: use mysql_real_escape_string

$user = mysql_real_escape_string($_POST['user'], $conn);
$pwd = mysql_real_escape_string($_POST['pwd'], $conn);

$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";

Best: use PDO and prepared statements

$stmt = $dbh->prepare("SELECT * FROM userdata WHERE UserName=':user' AND Password=PASSWORD(':pass')");
$stmt->bindParam(':user', $user);
$stmt->bindParam(':pass', $pass);
Code Magician
  • 23,217
  • 7
  • 60
  • 77
3

No. You should not be using addslashes() to escape your data. That's been obsolete for years. You should be either:

Plus using MySQL's Password() function is also poor pracdtive. Use hashes with salts. Bcrypt is my recommendation. Also, check out PHPass.

John Conde
  • 217,595
  • 99
  • 455
  • 496
2

Protecting against SQL injection is easy:

Filter your data.

This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.

Quote your data.

If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.

Escape your data.

Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn't a specific one, addslashes() is a good last resort.

Read more: http://phpsec.org/projects/guide/3.html#3.2

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201