I write this query to prevent SQL injection. But this code is not working. Can someone tell me where I have gone wrong with this? And I also need to know if this code prevents SQL injection attacks?
// 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
}
UPDATE 1 : above code working in this style
// 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
}
UPDATE 2 : my username and email come like this
// 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!';
}