Nee*_*eel 1 php sql sql-injection sqlbindparameter
我对 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();
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我的问题是:
1) 对于我的第二个代码,bind_result出于与第一个示例类似的任何安全原因,在获取所有结果时是否需要使用?
2)如果是,bind_result当我获取所有结果而不使用时如何使用prepare语句$id?
3)如果我使用第二个例子来获取所有结果,是否有任何安全问题?
你能帮我理解这一点吗...
1) 对于我的第二个代码,出于与第一个示例类似的任何安全原因,在获取所有结果时是否需要使用 bind_result?
号bind_result()无关安全。您可以对任何查询使用任何您希望的方法。
2) 如果是,当我获取所有结果而不使用 $id 时,如何将 prepare 语句与 bind_result 一起使用?
与任何其他查询完全相同的方式。实际上没有区别。并且拥有任何特定变量根本无关紧要。
3)如果我使用第二个例子来获取所有结果,是否有任何安全问题?
始终存在安全问题。但是在这个片段中没有来自 SQL 注入的领域。您可能希望检查 XSS 问题。
只是为了澄清你不明确的问题:
如果你是混淆bind_result使用bind_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;
}
Run Code Online (Sandbox Code Playgroud)
只需在连接前将 mysqli 设置为异常模式:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5248 次 |
| 最近记录: |