0

Hi I'm trying to create a database class which runs the queries. in that I sent the where condition as a parameter to a function like, id=$no AND name='vig'. now I want to replace the values with mysqli_real_escape_string, like id=mysql_real_escape_string($no). like this. how can I do that using preg_replace.

I got this regex when searching, but I don't know how to use it with preg_replace. '/(["\'])([^"\']+)\1/'

Vignesh
  • 1,045
  • 2
  • 17
  • 34
  • 1
    Have you tried anything? – Niet the Dark Absol Apr 11 '14 at 10:44
  • Also keep in mind that `mysql_real_escape_string` is not bulletproof. For a start you've missed a parameter to it, but you also have to ensure that every parameter of the query is quoted after being passed through the escape, otherwise stuff like ` OR 1=1 --` can slip through. My suggestion is to bite the bullet and move over to MySQLi with parameterised statements. – Polynomial Apr 11 '14 at 10:47
  • i'm in mysqli, but i'm not familiar with parameterized statements, is that possible to dynamically add those parameters to the query?@Polynomial – Vignesh Apr 11 '14 at 10:49

2 Answers2

2

Please don't do that !

Use prepared statements and parameterized queries using mysqli or PDO

How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
naab
  • 1,122
  • 1
  • 8
  • 25
1

This is the dangerest thing ever, I don't want to have written this:

<?php

$test="we will ' hack your db";
$test2=" ' OR SANITIZE";

$where='`$test` = \'1\' and `$test2` = \'2\'';

$where=preg_replace('/(\$[^ `]+)/e','mysql_real_escape_string($1)',$where);

echo($where);

?>

This is dangerous not only because of mysql_real_escape_string, but also because of preg_replace with the /e (execute) flag. It is just to see if and how it can be done.

If you have to learn anyway, please do learn prepared statements instead.

FrancescoMM
  • 2,845
  • 1
  • 18
  • 29