我编写此查询是为了防止 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!';
}