Is is bad practice to use array_walk with mysqli_r

2020-05-05 18:19发布

问题:

So I have a function called "escape" that looks like this:

function escape($string){
    $escaped_string = mysqli_real_escape_string($this->conn, $string);
    return $escaped_string;
}

I before running a query I send a variable (originated from user input obviously) here so its escaped for security reasons.

Now I know its possible to use array_walk to apply an array of values to this function, but I just want to know if there is any reason why I shouldn't? I know it sounds like a daft question but it would be nice and easy to apply it to an array of user inputted values rather than each variable.

Normally if when making a function I will do it this way:

function whatever($user_input){
    $user_input = $this->escape($user_input);
    $this->query("SELECT dog from pets where owner = '$user_input'");
     e.c.t. 
}

But if I have a lot of user inputted data from a form for example id rather just pass an array into the function and use array_walk on the escape function to save myself the hassle. But again is there any particular reason (from a security point of view) why this is not a good idea?

回答1:

YES, absolutely

The practice is the reincarnation of the infamous "magic quotes" feature, that once was a part of the language, but now thank goodness it is not.

Such an approach will do you no good but only a give a false feeling of security and spoil your data for no reason.

You must use prepared statements for all database interactions that involve PHP variables. This is the only 100% safe solution, and it makes the function in question obsolete.

Here I've got an example for the select query using prepared statements, https://phpdelusions.net/mysqli_examples/prepared_select

With a simple helper function it turns into much simpler and cleaner solution than that escaping-driven mess



标签: php mysqli