0

I am doing the following to protect subbmited data against sql attacks

$myusername = stripslashes($myusername);
$myusername = mysql_real_escape_string($myusername);
$mypassword = stripslashes($mypassword);
$mypassword = mysql_real_escape_string($mypassword);
$confirm_password = stripslashes($confirm_password);
$confirm_password = mysql_real_escape_string($confirm_password);
$fullname = stripslashes($fullname);
$fullname = mysql_real_escape_string($fullname);

Is there an easier way of doing this? This is a registration form and i have numerous fields to protect.

David Garcia
  • 3,056
  • 18
  • 55
  • 90
  • 1
    Look into prepared statements (such as [PDO](http://php.net/manual/en/book.pdo.php) or [`mysqli_prepare`](http://www.php.net/manual/en/mysqli.prepare.php)). – gen_Eric Apr 10 '12 at 18:09

2 Answers2

1

Is there an easier way of doing this?

Yes, first of all, disable automatic slashes, so you don't need to strip them. That will reduce the code already:

$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$confirm_password = mysql_real_escape_string($confirm_password);
$fullname = mysql_real_escape_string($fullname);

If you then use so called parametrized queries, you don't need to even call mysql_real_escape_string any longer as well but you can just safely use the variables.

Take note that you're using the unsafe variant of mysql_real_escape_string because you don't provide the database link to it.

See as well: Best way to stop SQL Injection in PHP.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
0

Yes, use PHP's PDO Object (PHP Database Object) and create prepared statements.

$dbh = new PDO('mysql:dbname=YOURDB;host=localhost', 'user', 'pass');
$sql = 'SELECT name FROM user WHERE id = :id';
$sth = $dbh->prepare($sql);
$sth->execute(array(':id' => 25);
$result = $sth->fetchAll();

It may also help you to know you can look for a PDO Wrapper to make your life much easier.

JREAM
  • 5,741
  • 11
  • 46
  • 84