0

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

1 回答 1

1

有人能告诉我我哪里出了问题吗?

我将在黑暗中刺伤并说您的第一个代码块(prep stmt)不起作用的原因在mysqli_stmt_num_rows的描述中给出:

返回结果集中的行数。mysqli_stmt_num_rows() 的使用取决于您是否使用 mysqli_stmt_store_result() 来缓冲语句句柄中的整个结果集。

...

而且我还需要知道这段代码是否可以防止 SQL 注入攻击?

使用准备好的语句,是的。

于 2013-02-02T05:18:09.023 回答