php - Want to replace certain words using preg_replace

205

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, likeid=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/'

212

Answer

Solution:

Please don't do that !

Use prepared statements and parameterized queries using mysqli or PDO

How can I prevent SQL injection in PHP?

215

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Stop cookies being set

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.