4

When should i use mysql_real_escape_string?

Is it only when i'm inserting rows into a database? Or only when i have user input?

Thanks

vitalyp
  • 671
  • 4
  • 12
  • 23
  • 1
    A good resource already on here on sql injection http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php – DeaconDesperado Mar 11 '11 at 20:40
  • The best I can tell `mysql_real_escape_string` may stop SQL injections at the cost of a buffer overflow. The function does not take a destination buffer size, so it relies on oversized strings and nice attackers who won't use "too many" escapes. – jww Feb 18 '19 at 03:43

4 Answers4

2

You should use mysql_real_escape_string() whenever you're building a query that will be run against the database. Any user input that is being used to build a database query should be run through this function. This will prevent sql injection attacks.

User inputs are your big area of concern when it comes to this.

Cody
  • 3,576
  • 2
  • 21
  • 29
2

You should use mysql_real_escape_string when you are inserting the value of a string into an SQL statement, and you are using the MySQL API.

$sql = "SELECT * FROM student WHERE foo = '" . $foo . "'";

Should be:

$sql = "SELECT * FROM student WHERE foo = '" .
        mysql_real_escape_string($foo) . "'";

However you should also consider using PDO with prepared statements and bind parameters instead of mysql_real_escape_string. This reduces the risk of errors.

Mark Byers
  • 719,658
  • 164
  • 1,497
  • 1,412
0

It will simply filter all special character which included in form data to prevent from SQL injection(SQL injection is a hacker tool for hacking website through some queries with form data}

0

always, apart from integers, there you use intval()

konsolenfreddy
  • 9,296
  • 23
  • 36