我正在将当前未受保护的查询更新为参数化查询,以防止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'];
答案 0 :(得分:2)
如果您查看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
}
答案 1 :(得分:1)
在获取行之前,您缺少对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'];