1

我对 MySQL 还很陌生,所以如果这听起来像一个愚蠢的问题,我深表歉意。

当我在学习 sql 安全性和防止 sql 注入时,我了解到在获取这样的 id 的结果时最好使用 bindparam:

//Prepare Statement
$stmt = $mysqli->prepare("SELECT * FROM my_table WHERE id=?");

if ( false===$stmt ) {
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param("i", $id);

if ( false===$rc ) {
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();

if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}


// Get the data result from the query. You need to bind results for each column that is called in the prepare statement above
$stmt->bind_result($col1, $col2, $col3, $col4);

/* fetch values and store them to each variables */
while ($stmt->fetch()) {
   $id = $col1;
   $abc = $col2; 
   $def = $col3; 
   $xyz = $col4;
}

$stmt->close();

$mysqli->close();

Atm,当我获取所有结果时,我正在使用这个:

$query= "SELECT * FROM my_table";  
$result=mysqli_query($connect, $query);

if (!$result)  
{  
  die('Error fetching results: ' . mysqli_error()); 
  exit();  
}

echo '<table border="1">'; // start a table tag in the HTML
//Storing the results in an Array
while ($row = mysqli_fetch_array($result))  //Creates a loop to loop through results
{  
    echo "<tr><td>" . $row['abc'] . "</td><td>" . $row['def'] . "</td><td>" . $row['xyz'] . "</td></tr>";  
}  
echo '</table>'; //Close the table in HTML

我的问题是:

bind_result1)对于我的第二个代码,出于类似于我的第一个示例的任何安全原因,我是否需要在获取所有结果时使用?

bind_result2)如果是,当我获取所有结果而不使用时,如何使用 prepare 语句$id

3) 如果我以获取所有结果的方式使用第二个示例,是否存在任何安全问题?

你能帮我理解这个吗...

4

1 回答 1

5

1)对于我的第二个代码,出于类似于我的第一个示例的任何安全原因,在获取所有结果时是否需要使用 bind_result ?

bind_result()。与安全无关。您可以对任何查询使用您希望的任何方法。

2) 如果是,当我获取所有结果而不使用 $id 时,如何使用带有 bind_result 的 prepare 语句?

与任何其他查询完全相同。实际上没有区别。并且有任何特定的变量根本不重要。

3) 如果我以获取所有结果的方式使用第二个示例,是否存在任何安全问题?

总是存在安全问题。但是这个片段中没有来自 SQL 注入领域的内容。您可能希望检查 XSS 问题。

只是为了澄清您的模棱两可的问题:
如果您对 感到困惑bind_resultbind_param这里有一条经验法则:您必须为要进入查询的每个变量使用占位符(因此 bind_param())。总是。没有例外。

prepare()根据这条规则,您可以简单地判断在任何特定情况下是否需要使用。

此外,在第一个示例中不需要如此冗长而冗长的代码。

$stmt = $mysqli->prepare("SELECT * FROM my_table WHERE id=?");
$rc = $stmt->bind_param("i", $id);
$rc = $stmt->execute();
$stmt->bind_result($id, $abc, $def, $xyz);
while ($stmt->fetch()) {
  echo $id;
}

只需在连接之前将 mysqli 设置为异常模式:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
于 2014-01-02T17:47:41.090 回答