我无法理解如何清理php以防止SQL注入,并希望有人能够向我解释为了使我的代码安全而需要更改的内容?
<?php
$dbConnection = mysqli_connect('****', '****', '****', 'db');
$query = "INSERT INTO `table` (`1`, `2`, `3`) VALUES ('$_POST[1]', '$_POST[2]', '$_POST[3]')";
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
?>
答案 0 :(得分:2)
MySQLi支持prepared statements,这比手动转义更好:
由于您使用的是程序化MySQLi,以下是一个示例:
/* create a prepared statement */
if ($stmt = mysqli_prepare($dbConnection, "INSERT INTO `table` (`1`, `2`, `3`) VALUES (?, ?, ?)"))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "sss", $_POST[1], $_POST[2], $_POST[3]);
/* execute query */
if(mysqli_stmt_execute($stmt))
{
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
}
else
{
echo "Error occurred: " . mysqli_error($dbConnection);
}
/* close statement */
mysqli_stmt_close($stmt);
}
答案 1 :(得分:1)
要防止SQL注入,您可以使用预准备语句。您需要更多mysqli_
函数:
通过这些,您可以编写如下内容:
$dbConnection = mysqli_connect('****', '****', '****', 'db');
// prepare the query
$query = mysqli_prepare( $dbConnection, "INSERT INTO `table` (`1`, `2`, `3`) VALUES (?, ?, ?)";
// bind parameters; 2nd parameter is for data-types
mysqli_stmt_bind_param( $query, "sss", $_POST[1], $_POST[2], $_POST[3] );
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
答案 2 :(得分:0)
如果您想继续使用旧的mysql_ *函数,请查看http://php.net/manual/en/function.mysql-real-escape-string.php
$datapoint1 = mysql_real_escape_string($_POST[1]);
...
$query = "INSERT INTO `table` (`1`, `2`, `3`) VALUES ('$datapoint1', '$datapoint2', '$datapoint3')";
答案 3 :(得分:0)
您可以使用预准备语句或mysqli_real_escape_string