doubei2340 2014-04-03 21:28
浏览 71
已采纳

使用mysql_real_escape_string的速度

My question is: is it faster to do an operation for every item in an array even if it doesn't require it or to check if it requires it first.

Example: I have a loop that is set up like this [metacode]

foreach($array as $varkey => $varvalue){
    if(!is_array($varkey)) $varvalue = mysql_real_escape_string($varvalue); 
}

One of my coworkers believes that we should only use the mysql_real_escape_string function is the $varvalue has an apostrophe in it. That would require the use of a strstr() or preg_match() to see if an apostrophe was present before using mysql_real_escape_string, like so:

foreach($array as $varkey => $varvalue){
    if(!is_array($varkey)){
        if(strstr("'", $varvalue) $varvalue = mysql_real_escape_string($varvalue); 
    }
}

Is there any speed/security advantage with going one or the other?

*ps. I know we should probably be using prepared statements with PDO or mysqli_. That's another conversation we need to have internally on another day.*

  • 写回答

2条回答 默认 最新

  • duanji9378 2014-04-03 21:38
    关注

    The mysql_real_escape_string() already searches the string for apostrophes and other characters, and escapes only the characters it is designed to do. And it's written in C, like built-in functions in PHP, so it's really quite fast.

    preg_match() is not aware of the MySQL connection character set, so it has a chance of giving a false negative -- in other words, a case where you should escape the string, but your test tells you not to.

    As other people have pointed out, you are in the realm of pointless micro-optimization when you decide to save code or performance by testing the string. You have probably already wasted more computing resources as well as human attention by posting this question to StackOverflow than you could ever save by optimizing when you escape the strings.

    Just call the escaping function and then shift your attention to converting your code to PDO, protecting your queries with parameters.

    I sympathize with the size of the project to convert your code to PDO, and the difficulty in justifying the change. It's hard to convince the powers that be of the worth of the project, when it results in a vague promise of greater "security" instead of any functional change.

    You could combine the effort with some other refactoring that gives some more concrete benefits, like creating a wrapper function for all queries so you can audit or profile database activity. That may convince the decision makers of the value of the project.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?