php mysqli参数化查询无法运行

cedebl8k  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(325)

我正在将当前未受保护的查询更新为参数化查询,以防止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'];
0g0grzrc

0g0grzrc1#

如果你看一下文档 mysqli_stmt_fetch 您将看到以下描述:
将准备好的语句中的结果提取到绑定变量中
所以如果你想走这条路,你需要 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
}
ih99xse1

ih99xse12#

你错过了一个电话 mysqli_stmt_get_result 获取行之前:

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

echo $row['id'];

相关问题