什么是最简单和最有效的消毒方法:
$q = "SELECT * FROM `admin` "
."WHERE `username`=' ".$_POST["username"]."' "
."AND `passcode`=' ".$_POST["password"]."' "
另外,我正在学习 PHP,所以如果您能提供解释、提示、建议或更多清理内容以防止 SQL 注入的方法,将不胜感激
我喜欢使用 $mysqli prepared statements
- 这是来自 PHP 站点的示例:
说明(请参阅底部以获取使用您的代码的示例):
您将查询中的变量替换为?
标记,然后再将bind
变量替换为标记。
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
使用您的代码的示例:
$q = "SELECT * FROM `admin` "
."WHERE `username`= ? AND passcode = ?";
/* create a prepared statement */
if ($stmt = $mysqli->prepare($q)) {
/* bind parameters for markers */
$stmt->bind_param("ss", $_POST['username'], $_POST['password']);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch(); // This can also be while($stmt->fetch()){ Code here }
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
如果你真的必须知道它会是这样的:
$q = "SELECT * FROM `admin` "
."WHERE `username`=' ".mysql_real_escape_string($_POST["username"])."' "
."AND `passcode`=' ".mysql_real_escape_string($_POST["password"])."' "
但正如其他人所说,您应该使用最有可能的 PDO 或 mysqli 因为所有 mysql_ 命令都已弃用。