简体   繁体   English

PHP MySQLi参数化查询无法正常工作

[英]PHP MySQLi Parameterized Query not functioning

I am updating my current unprotected queries to parameterized ones to protect from SQL Injection. 我正在将当前未受保护的查询更新为参数化查询以防止SQL注入。

I have spent a few hours trying to sort this however cant find the issue, any help much appreciated. 我花了几个小时尝试对此进行排序,但无法找到问题,任何帮助都非常感激。

BEFORE (echo $row['storeID'];) works before 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);

AFTER

$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);

This echo should work but using statements it does not 这个echo应该可以工作,但是使用它不能的语句

 echo $row['storeID']; 

If you look at the documentation for mysqli_stmt_fetch you'll see this description: 如果你查看mysqli_stmt_fetch的文档,你会看到这个描述:

Fetch results from a prepared statement into the bound variables 将预准备语句的结果提取到绑定变量中

So if you want to go this route, you'll need to ue mysqli_stmt_bind_result as well: 所以如果你想走这条路,你还需要你的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.
}

Now, with each iteration of the loop, the bound result variables are given the value from the result set. 现在,随着循环的每次迭代,绑定结果变量都被赋予结果集中的值。


However, I'd strongly suggest moving to PDO, which is far less verbose: 但是,我强烈建议转向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
}

You were missing a call to mysqli_stmt_get_result before fetching the row: 在获取行之前,您错过了对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'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM