gpt4 book ai didi

PHP MySQLi 参数化查询不起作用

转载 作者:可可西里 更新时间:2023-11-01 08:08:49 25 4
gpt4 key购买 nike

我正在将当前未 protected 查询更新为参数化查询,以防止 SQL 注入(inject)。

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

BEFORE (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 应该有效,但 using 语句却无效

 echo $row['storeID']; 

最佳答案

如果您查看 mysqli_stmt_fetch 的文档你会看到这样的描述:

Fetch results from a prepared statement into the bound variables

所以如果你想走这条路,你需要使用 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.
}

现在,在循环的每次迭代中,绑定(bind)的结果变量都会从结果集中获得值。


但是,我强烈建议转向 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 MySQLi 参数化查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53937570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com