Vignesh
Vignesh

Reputation: 1063

Want to replace certain words using preg_replace

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/'

Upvotes: 0

Views: 83

Answers (2)

FrancescoMM
FrancescoMM

Reputation: 2960

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.

Upvotes: 1

naab
naab

Reputation: 1140

Please don't do that !

Use prepared statements and parameterized queries using mysqli or PDO

How can I prevent SQL injection in PHP?

Upvotes: 2

Related Questions