1

Possible Duplicate:
Best way to prevent SQL Injection in PHP

I escape quotation marks via addslashes($str).

When i save the input from text fields to a MySQL database, is that a sufficient protection against MySQL injections or do I need to filter the input further because you can bypass this escape method? Or is there any better way to do this?

Community
  • 1
  • 1

5 Answers5

2

You should read about prepared statements in PDO: http://www.php.net/manual/en/pdo.prepared-statements.php

mdziekon
  • 3,531
  • 3
  • 22
  • 32
1

Escaping quotes is definitely not enough. The safest thing to do is to use parameter binding. See the docs for mysqli_stmt::bind_param.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Yes, there is. You can check all parameters for any of the following things, depending on expected values:

  • Is the value of the variable something meaningful?
  • Is the value of the variable within a reasonable value range?
  • Is the value of the variable inside a predefined maximum length?

Those are some elementary checks that can save you a lot of trouble. Also, to avoid more problems:

  • Always filter file uploads, and never execute anything uploaded.
  • Never, ever execute SQL or evaluate code that has a direct part of user input. Always parse your inputs first, so that you are certain it does not contain any abnormalities.
Ioannis Karadimas
  • 7,746
  • 3
  • 35
  • 45
-1

You can do excaping like this:

<?php  
    $query = mysql_query("SELECT id FROM users WHERE username =   '".mysql_real_escape_string($username)."' AND password = '".mysql_real_escape_string($password)."'");  
?>  
Jordizle
  • 252
  • 1
  • 5
-1

I would suggest using mysql_real_escape_string or similar function (depending on what DB access methodology you are using).

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Building queries by mashing together strings leaves too much room for error. Use bound parameters. That function also comes with a big red "use something else" alert in the PHP manual. – Quentin Jul 18 '12 at 18:37
  • 1
    Yes, but many people do not necessarily want to use some database abstraction layer or want the additional overhead that prepared statements may bring for cases where you are only doing single data inserts (as opposed to performing the same query multiple times with different data where prepared statements really shine performance-wise). Also some users may not have MYSQLi extension available on their server or the ability/know how to install it. – Mike Brant Jul 18 '12 at 18:42