PHP MySQLi参数化查询不起作用

我正在将当前未受保护的查询更新为参数化查询,以防止受到SQL注入.

我花了几个小时试图对这个问题进行排序,但是找不到问题,非常感谢任何帮助.

在(echo $row [‘storeID’];)之前工作

$storeName = mysqli_real_escape_string($conn,$_GET['store']); 
$query = "SELECT * FROM stores WHERE storeName = '$storeName'";
$results = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($results);

$storeName = $_GET['store'];
$stmt = mysqli_prepare($conn, "SELECT * FROM stores WHERE storeName = ?");
mysqli_stmt_bind_param($stmt, "s", $storeName);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);

该回显应该起作用,但是使用语句却不起作用

 echo $row['storeID']; 

解决方法:

如果查看mysqli_stmt_fetch的文档,则会看到以下说明:

Fetch results from a prepared statement into the bound variables

因此,如果您想走这条路线,还需要ue mysqli_stmt_bind_result

$storeName = $_GET['store'];
$stmt = mysqli_prepare($conn, "SELECT * FROM stores WHERE storeName = ?");
mysqli_stmt_bind_param($stmt, "s", $storeName);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $col1, $col2, $col3,...);
while (mysqli_stmt_fetch($stmt)) {
    // do stuff with $col1, $col2, etc.
}

现在,在循环的每次迭代中,为绑定的结果变量提供结果集中的值.

但是,我强烈建议您改用PDO,这要冗长得多:

$storeName = $_GET['store'];
$stmt = $db->prepare("SELECT * FROM stores WHERE storeName = ?");
$stmt->execute([$storeName]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// now you have a simple array with all your results
foreach ($rows as $row) {
    // do stuff with $row
}
上一篇:如何删除php循环以减少mysql查询数量


下一篇:mysql-尝试使用外键制作表时出现错误