为了防止sql注入,mysqli_real_escape_string()只对逗号分隔的字符串应用一次就足够了吗?

时间:2014-08-05 20:22:43

标签: php sql-injection

如果有人发布此内容并且我错过了,我会道歉...我用谷歌搜索并搜索了类似的问题,如果它存在,我就错过了。

场景:用户输入逗号分隔的输入。需要展开字符串,每个部分用于更新不同的表行。一次应用mysqli_real_escape_string()就足够了:

<?php include 'connect.php';

$ExplodedCommaString = explode(",", mysqli_real_escape_string($cxn, $_GET['userinput']));
$Count = count($ExplodedCommaString);

for ($i = 0; $i < $Count; $i++) {
    $myID = $ExplodedCommaString[$i];
    $sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '$myID'");
}
?>

或每个必须通过for循环应用mysqli_real_escape_string?

<?php include 'connect.php';

$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);

for ($i = 0; $i < $Count; $i++) {
    $myID = $ExplodedCommaString[$i];
    $sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '".mysqli_real_escape_string($cxn, $myID)."'");
}
?>

那么,在逗号分隔的字符串上应用一次并爆炸字符串,或者爆炸字符串然后在for循环的每次迭代中应用它?

1 个答案:

答案 0 :(得分:1)

通过使用准备好的陈述,您不必担心自己逃避内容,或者如何正确地执行此操作。

示例:

<?php include 'connect.php';

$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);

for ($i = 0; $i < $Count; $i++) {
    $myID = $ExplodedCommaString[$i];
    // replace your raw var with ? in the sql statement
    $sql = "UPDATE myTable SET myValue = 'y' WHERE id = ?";
    // run the prepare method
    $stmt = $conn->prepare($sql);
    // bind the '?' in the sql statement to $myID of type int
    // I'm assuming it's an int here, if it's a string change the 'i' to an 's'
    $stmt->bind_param('i', $myID);
    // and run it
    $stmt->execute();
}
?>

Some further reading, examples, and discussion.