我编写此查询以防止SQL注入。但是这段代码不起作用。有人能告诉我这里出了什么问题吗?我还需要知道此代码是否可以防止SQL注入攻击?
// Make sure the email address and username are available:
$q = "SELECT *
FROM
(
SELECT userName, NULL AS email FROM Login
UNION
SELECT NULL AS username, email FROM contact
) s
WHERE username = ? OR email = ?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
// Execute the query:
mysqli_stmt_execute($stmt);
// Get the number of rows returned:
$rows = mysqli_stmt_num_rows($stmt);
if ($rows == 0) { // No problems! Going to next page
}
更新1 :以上代码工作的代码
// Make sure the email address and username are available:
$q = "SELECT *
FROM
(
SELECT userName, NULL AS email FROM Login
UNION
SELECT NULL AS username, email FROM contact
) s
WHERE username = '$username' OR email = '$email'";
$r = mysqli_query ($dbc, $q);
// Get the number of rows returned:
$rows = mysqli_num_rows($r);
if ($rows == 0) { // No problems! Going to next page
}
更新2 :我的用户名和电子邮件就像这样
// Check for a username:
if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $_POST['username'])) {
$username = mysqli_real_escape_string ($dbc, $_POST['username']);
} else {
$reg_errors['username'] = 'You have not entered your username!';
}
// Check for an email address:
if (!empty( $_POST['email'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string ($dbc, $_POST['email']);
} else {
$reg_errors['email'] = 'You are NOT entered a valid email address!';
}
} else {
$reg_errors['email'] = 'Your email address field can not be empty!';
}
答案 0 :(得分:1)
有人可以告诉我这里出了什么问题吗?
我将在黑暗中进行一次尝试,并说明你的第一个代码块(准备工作)不起作用的原因在mysqli_stmt_num_rows的说明中给出:
返回结果集中的行数。指某东西的用途 mysqli_stmt_num_rows()取决于你是否使用过 mysqli_stmt_store_result()缓冲整个结果集 陈述句柄。
...
我还需要知道此代码是否可以防止SQL注入攻击?
使用准备好的陈述,是的。