简体   繁体   English

jQuery验证远程 - 检查电子邮件是否已存在

[英]jQuery Validate Remote - Check if email already exists

I have a bit of an issue getting jQuery Validation to check if an email address already exists in a mysql table. 我有一个问题,让jQuery Validation检查mysql表中是否已存在电子邮件地址。

Every time I submit the form, it tells me the email already exists, even though I know it doesn't. 每次我提交表单时,它都会告诉我电子邮件已经存在,即使我知道它没有。

Here's the code I have: 这是我的代码:

validation.js validation.js

$(document).ready(function () {

    $('#signup').validate({ 
        errorLabelContainer: "#cs-error-note",
        wrapper: "li",
        rules: {
            email: {
                required: true,
                email: true,
                remote: {
                    url: "check-username.php",
                    type: "post"
                }
            }
        },
        messages: {
            email: {
                required: "Please enter your email address.",
                email: "Please enter a valid email address.",
                remote: "Email already in use!"
            }
        },
        submitHandler: function(form) {
            form.submit();
        }
    });

});

check-username.php 入住username.php

<?php
    require('../../private_html/db_connection/connection.php');

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $query = $conn->prepare("SELECT * FROM 'user_accounts' WHERE email = '" . $_POST['email'] . "'");
    $query->execute();

    if( $query->rowCount() > 0 ){
        echo 'true';
    }
    else{
        echo 'false';
    }
?>

Your help is much appreciated! 非常感谢您的帮助!

You have to change the row count if / else condition in query 如果查询中有/ else条件,则必须更改行计数

Script 脚本

<script>
$(document).ready(function () {
    $('#signup').validate({ 
    errorLabelContainer: "#cs-error-note",
    wrapper: "li",
    rules: {
        email: {
            required: true,
            email: true,
                remote: {
                    url: "check-username.php",
                    type: "post"
                 }
        }
    },
    messages: {
        email: {
            required: "Please enter your email address.",
            email: "Please enter a valid email address.",
            remote: "Email already in use!"
        }
    },
    submitHandler: function(form) {
                        form.submit();
                     }
    });
});
</script>

HTML HTML

<form class="form-inline" role="form" id="signup">
    <div class="form-group">
    <label for="email">Email address:</label>
        <input type="email" class="form-control" name="email" id="email">
    </div>
</form>

PHP PHP

Warning Do not use this PHP code reason rowCount() may not work so skip it and jump to code at bottom of answer. 警告不要使用此PHP代码原因rowCount()可能无法正常工作,因此跳过它并跳转到答案底部的代码。

<?php
    require('../../private_html/db_connection/connection.php');
    $conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);    
    if(isset($_POST['email'])) {
        $email = $_POST['email'];
        $query = $conn->prepare("SELECT email FROM user_accounts WHERE email = '$email'");
        $query->execute();
        if( $query->rowCount() > 0 ){
            echo 'false';
        } else {
            echo 'true';
        }
    }
?>

Edit: As @Jay Blanchard very consistent and dead sure that above code will not work 编辑:因为@Jay Blanchard非常一致并且确定上面的代码不起作用

  • rowCount() doesn't work for SELECT statements. rowCount()不适用于SELECT语句。 stackoverflow.com/a/31569733/1011527 stackoverflow.com/a/31569733/1011527

  • Nope, this will not work because rowCount() doesn't work for SELECT statements. 不,这不起作用,因为rowCount()不适用于SELECT语句。 You're not getting a row count at all. 你根本没有获得行数。

  • Try echoing $query->rowCount() and you'll see the issue 尝试回显$ query-> rowCount(),你会看到问题

and makes me wonder How the above code is working on my live server when It shouldn't so I done some digging and found this; 并让我想知道上面的代码是如何在我的实时服务器上工作的时候它不应该这样我做了一些挖掘并找到了这个;

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. 如果关联的PDOStatement执行的最后一个SQL语句是SELECT语句,则某些数据库可能会返回该语句返回的行数 However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications. 但是,并不保证所有数据库都有这种行为,不应依赖于便携式应用程序。

and this 和这个

For most databases , PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. 对于大多数数据库 ,PDOStatement :: rowCount()不返回受SELECT语句影响的行数。 Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. 相反,使用PDO :: query()发出带有与预期SELECT语句相同的谓词的SELECT COUNT(*)语句,然后使用PDOStatement :: fetchColumn()来检索将返回的行数。 Your application can then perform the correct action. 然后,您的应用程序可以执行正确的操作

Source of Above statements php.net manuals 以上语句来源php.net手册

In both above statements, some databases and For most databases rowCount() does work but on other-hand 在上述两个语句中, 一些数据库大多数数据库 rowCount() 确实可以工作,但另一方面

  • should not be relied on for portable applications 不应该依赖于便携式应用程序
  • use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. 使用PDOStatement :: fetchColumn()来检索将返回的行数。 Your application can then perform the correct action. 然后,您的应用程序可以执行正确的操作

As OP only wants the count of rows and not all the data of all the rows so can be also done like this. 由于OP只想要行数而不是所有行的所有数据,所以也可以这样做。 Credit goes to @Jay Blanchard 归功于@Jay Blanchard

Use This Code Example 使用此代码示例

made some changes in PHP, use isset function. 在PHP中做了一些更改,使用了isset函数。

<?php
    require('../../private_html/db_connection/connection.php');
    $conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);    
    if(isset($_POST['email'])) {
        $email = $_POST['email'];
        $query = $conn->prepare("SELECT email FROM user_accounts WHERE email = '$email'");
        $query->execute();
        $rows = $query->fetchAll();
        $total_rows = count($rows);
            if( $total_rows > 0 ){
                echo 'false';
            } else {
                echo 'true';
            }
    }
?>

See in Action 见行动

rowCount() will not work in the situation. rowCount()在这种情况下不起作用。 From the docs: 来自文档:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. PDOStatement :: rowCount()返回由相应PDOStatement对象执行的最后一个DELETE,INSERT或UPDATE语句影响的行数。

Note that it doesn't return anything for a SELECT statement. 请注意,它不会为SELECT语句返回任何内容。 To get the row count in your code you would do this: 要获取代码中的行数,您可以执行以下操作:

if(isset($_POST['email'])) {
    $email = $_POST['email'];
    $query = $conn->prepare("SELECT email FROM user_accounts WHERE email = ?");
    $query->execute(array($email));
    $rows = $query->fetchAll();
    $num_rows = count($rows);
    if( $num_rows > 0 ){
        echo 'true - email exists';
    } else {
        echo 'false - email does not exist';
    }
}

In order to avoid the possibility of SQL Injection Attack I use a prepared statement , sending an array (of one) containing the values to be used in the query in the execute() statement. 为了避免SQL注入攻击的可能性,我使用一个预准备语句 ,在execute()语句中发送一个包含要在查询中使用的值的数组(一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM