准备好的语句不适用于PHP

时间:2014-08-05 16:14:51

标签: php mysql sql mysqli sql-injection

我目前正在尝试使用预准备语句来阻止SQL注入,但每次我尝试加载此代码时都会失败,我做错了什么?

<?php
$mysqli = new mysqli("127.0.0.1", "root", "root", "Database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$stmt = $mysqli->prepare('SELECT * FROM `Users`');
$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row[0] . "<br>";
}
/* close statement */
$stmt->close();

/* close connection */
$mysqli->close();
?>

1 个答案:

答案 0 :(得分:0)

使用预准备语句,您应该绑定结果,如下所示:

    $stmt = $mysqli->prepare('SELECT * FROM `Users`')) {
    $stmt->execute();   
    $stmt->store_result();
    $stmt->bind_result($param1, $param2...);
    $stmt->fetch();

不幸的是$stmt->bind_param()不接受params数组

所以你可以用这样的东西来获取它们:

$stmt->execute();   
$stmt->store_result();
$rows = $stmt->num_rows;
$meta = $stmt->result_metadata(); 

    while ($field = $meta->fetch_field()) 
    { 
        $params[] = &$row[$field->name]; 
    }
call_user_func_array(array($stmt, 'bind_result'), $params); 
while ($stmt->fetch()) { 
    foreach($row as $key => $val) 
    { 
        $c[$key] = $val; 
    } 
    $result[] = $c; 
} 

$stmt->close(); 

数组$result将包含您需要的结果。