0

I am using mysql_real_escape_string($_REQUEST['page']) in my code. Is it able to prevent SQL Injection in my php code else i will have to do more protection ?

Thanks

Ajay
  • 1

3 Answers3

0

Yes, but prepared statements are better.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • It is much harder to accidentally fail to convert a variable if you are doing it as part of prepared statement syntax then if you are concatenating half a dozen variables into a string. – Quentin Jun 13 '10 at 21:27
0

Personally, I would drop the mysql extension and migrate to the mysqli extension. The problem with the mysql extension is that its old, and quite frankly, its rather easy to forget to escape something.

mysqli has support for prepared statements and it also has an OOP API which makes it way easier to develop.

When you start using prepared statements, it makes it easier to keep track of your parameters. It also auto escapes them for you.

Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
0

I would also recommend using prepared statements in most cases, but it's only necessary when inserting data that came from a user that could be a string. Prepared statements are more expensive (performance), so when you can avoid them you probably should. There are many benefits of using prepared statements and/or database transactions. You should probably look into it, unless you already have.

If you receive numerical values from, for example, a form, you just need to ensure data quality by converting the input into a number (any input from GET or POST are ALWAYS regarded as strings by PHP, unless you convert them), and any malicious code will be removed.

Here's an example:

$intCarAge = (int) $_POST['car_age'];
mysqli_query("UPDATE cars SET car_age = " . $intCarAge . " WHERE id = '123' ");

The "(int)" converts the data in the input variable $_POST['car_age'] to a number (integer). It can be added before any variable in your code. Any letters inside the variable will be removed and any numbers will be kept. You can read more about number conversion here.

Hope I was of any help!

Emanuel
  • 831
  • 6
  • 14