2

Possible Duplicate:
Best way to stop SQL Injection in PHP

I would like to know which functions is best to use to prevent MySQL injections

There are plenny of functions I can use to prevent sql injections, such as:

  • mysql_real_escape_string
  • mysqli_real_escape_string
  • addslashes
  • casting values (intval etc...) for numbers
  • htmlentities with ENT_QUOTES
  • or simply remove the ' or "

I want to standardize my code using the best and faster anti-SQL-injections method and I would like to know which one should I use for high traffic sites.

Community
  • 1
  • 1
Xin Qian Ch'ang
  • 665
  • 1
  • 7
  • 13
  • 1
    Just because this topic comes up *weekly* doesn't make it a good question. Please use the search function. – mario Nov 21 '11 at 04:14
  • Are you using mysql_query(), mysqli_query(), PDO or something else? – hafichuk Nov 21 '11 at 04:15
  • 1
    Questions that have 'best' or similar words in the title are rarely the right question to ask on SO. http://stackoverflow.com/faq – vascowhite Nov 21 '11 at 04:18

2 Answers2

6

You shouldn't use htmlentities for saving data to a database, addslashes isn't 100% secured (some character sets can still make it vulnerable), using mysql_ or mysqli_ is dependent on the driver you're using and not interchangable. Basically, its not a matter of speed or performance - the only right thing to do is using the escape function that comes with your driver (pdo::escape or mysql[I]_real_escape_string) for strings and casting integers/floats to their correct type.

shesek
  • 4,584
  • 1
  • 28
  • 27
  • how addslashes ins't 100% secure? – Xin Qian Ch'ang Nov 21 '11 at 04:20
  • @XinQianCh'ang: http://stackoverflow.com/questions/860954/examples-of-sql-injections-through-addslashes (found via [the search function](http://stackoverflow.com/search?q=php%20why%20isn't%20addslashes%20secure%20against%20sql%20injection?)) – mario Nov 21 '11 at 04:23
  • Look at the link in the second answer, not the first answer. – shesek Nov 21 '11 at 04:46
0

To give you a simple answer, you can use mysql_real_escape_string

http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

http://www.osempire.com/php-injection-attacks-guide

To give you a better answer, try reading Theo's answer in How can I prevent SQL injection in PHP?

I assume you are in the middle of the project already. Once you finish, I suggest learning a new framework like CodeIgniter, Yii and CakePHP to speed up development.

Community
  • 1
  • 1
Victor
  • 2,864
  • 1
  • 12
  • 20