我目前正在尝试使用准备好的语句来防止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();
?>

最佳答案

使用准备好的语句,应将结果绑定如下:

    $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将包含您需要的结果。

关于php - 准备好的语句在PHP中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25143632/

10-16 08:36