根据条件检查数据库结果

时间:2016-05-17 16:40:32

标签: javascript php html mysql ajax

我的问题如下。我想要javascript来检查数据库中是否存在值。我有一个javascript函数,它检查数据库中是否存在电子邮件地址。那个工作正常,所以我复制了它并将其更改为匹配不同的输入字段,这应检查是否存在值(woonplaats)。现在,它总是显示消息'plaatsnaam bestaat niet',即使它确实存在。带有检查数据库和javascript的SQL的HTML,PHP代码都在同一个PHP文件中。我知道PHP检查echo,但我只想让javascript执行检查。

在我的代码下面:

HTML:

<form action="" onSubmit="return !!checkMailStatus() & checkCityStatus();" method="post" id="registration">
<input type="email" name="email" id="email" placeholder="E-mailadres" required/>
<input type="text" name="keyword" id="keyword" placeholder="Woonplaats" value="">
<button type="submit" name="register" class="btn-red">Registreren!</button>
  </form>

PHP:

if(isset($_POST['register'])) {

    $email = $_POST['email'];
    $keyword = $_POST['keyword'];

    $check_d = $db->query("SELECT id FROM users WHERE email='".$email."'");
    $check_d = $check_d->num_rows;
    if($check_d == 1) {
        echo 'E-mailadres bestaat al';
    }

    $check_pnl = ("SELECT woonplaats 
                   FROM `locatie` 
                   WHERE    woonplaats='".$keyword."'");
    $check_pnl = $check_pnl->num_rows;
    if($check_pnl == 0) {
        echo 'Plaatsnaam Bestaat Niet';
    }

使用Javascript:

<script>
function checkMailStatus(){
    //alert("came");
var email=$("#email").val();
$.ajax({
    type:'post',
        url:'',
        data:{email: email},
        success:function(msg){
        alert('Gebruik een ander e-mail adres'); 
        return false; //prevent submit from submitting     
        }

 });
}
</script>
<script>
function checkCityStatus(){
    //alert("came");
var keyword=$("#keyword").val();
$.ajax({
    type:'post',
        url:'',
        data:{keyword: keyword},
        success:function(msg){
        alert('Plaatsnaam bestaat niet');
        return false; //prevent submit from submitting     
        }

 });
}
</script>

基于Pioz和RAJDEEP的警告Paul我改变了以下内容:

index.php中的

我将javascript代码更改为:

<script>

        var regForm     = $("#registration");

        regForm.submit(function(evt){
            // PREVENT FORM FROM DEFAULT BEHAVIOUR: SUBMITTING...
            evt.preventDefault();

            // IF BOTH CONDITIONS ARE SATISFIED... SUBMIT THE FORM MANUALLY...
            if(checkMailStatus() && checkCityStatus()){
                // SHIP THE FORM
                $(this).submit();
            }

        });


        function checkMailStatus(){
            var email       = $("#email").val();
            var returnVal   = 0;
            $.ajax({
                type:'post',
                    url:'check.php',
                    data:{email: email, checkMail: true},

                    success:function(msg){
                        if(msg == "0"){
                            alert('Gebruik een ander e-mail adres'); 
                        }else{
                            returnVal = 1;
                        }
                    }

             });
             return returnVal;
        }

        function checkCityStatus(){
            var keyword     = $("#keyword").val();
            var returnVal   = 0;
            $.ajax({
                type:'post',
                    url:'check.php',
                    data:{keyword: keyword, checkCity: true},

                    success:function(msg){
                        if(msg == "0"){
                            alert('Plaatsnaam bestaat niet');  
                        }else{
                            returnVal = 1;
                        }  
                    }
            });
             return returnVal;
        }
    </script>

我也创建了CHECK.PHP:

if($_POST['checkMail'] == "true"){ 
        $check_d    = $db->query("SELECT id FROM users WHERE email='".$email."'");
        $check_d    = $check_d->num_rows;
        if($check_d == 0) {
            echo "0";
        }else{
            // ECHO A FLAG TO SHOW THAT EVERYTHING WORKS FINE: ZERO ISSUE WAS FOUND
            echo "1";
        }
        }

        if($_POST['checkCity'] == "true"){
        $check_pnl  = ("SELECT woonplaats 
                       FROM `locatie` 
                       WHERE    woonplaats='".$keyword."'");
        $check_pnl  = $check_pnl->num_rows;
        if($check_pnl == 0) {
            echo "1";
        }else{
            // ECHO A FLAG TO SHOW THAT EVERYTHING WORKS FINE: ZERO ISSUE WAS FOUND
            echo "0";
        }
        }

2 个答案:

答案 0 :(得分:1)

除了在2个单独的文件中有2个函数之外,没有必要为这两个函数创建多个脚本块。如果你愿意,这是你的另一条路线:

<强> HTML

    <form action="" method="post" id="registration">
        <input type="email" name="email"    id="email"      placeholder="E-mailadres" required/>
        <input type="text"  name="keyword"  id="keyword"    placeholder="Woonplaats"    value="">
        <button type="submit" name="register" class="btn-red">Registreren!</button>
    </form>

<强> JAVASCRIPT

    <script>

    // MAKE SURE YOU ADD THE FOLLOWING TO YOUR JAVASCRIPT AS YOU ARE USING JQUERY, NOT RAW JS.

    (function ($) {             //<== THIS LINE IS NEW
        $(document).ready(function(e) {     //<== THIS LINE IS NEW
        var regForm     = $("#registration");

        regForm.submit(function(evt){
            // PREVENT FORM FROM DEFAULT BEHAVIOUR: SUBMITTING...
            evt.preventDefault();

            // IF BOTH CONDITIONS ARE SATISFIED... SUBMIT THE FORM MANUALLY...
            if(checkMailStatus() && checkCityStatus()){
                // SHIP THE FORM
                $(this).submit();
            }

        });


        function checkMailStatus(){
            var email       = $("#email").val();
            var returnVal   = 0;
            $.ajax({
                type:'post',
                    url:'check.php',
                    dataType:'json',
                    data:{email: email},

                    success:function(msg){
                        if(msg){
                            if(msg.message){
                                alert(msg.message); 
                            }
                        }else{
                            returnVal = 1;
                        }
                    }

             });
             return returnVal;
        }

        function checkCityStatus(){
            var keyword     = $("#keyword").val();
            var returnVal   = 0;
            $.ajax({
                type:'post',
                    url:'check.php',
                    dataType:'json',
                    data:{keyword: keyword},

                    success:function(msg){
                        if(msg){
                            if(msg.message){
                                alert(msg.message); 
                            }                                
                        }else{
                            returnVal = 1;
                        }  
                    }
            });
             return returnVal;
        }
        });      //<== THIS LINE IS NEW
    })(jQuery); //<== THIS LINE IS NEW
    </script>

<强> PHP

            <?php

        $response = array("message"=>null);
        if(isset($_POST['register'])) {

            $email      = $_POST['email'];
            $keyword    = $_POST['keyword'];

            $check_d    = $db->query("SELECT id FROM users WHERE email='".$email."'");
            $check_d    = $check_d->num_rows;
            if($check_d != 1) {
                $response['message']    = 'E-mailadres bestaat al';
            }else{
                // ECHO A FLAG TO SHOW THAT EVERYTHING WORKS FINE: ZERO ISSUE WAS FOUND
                $response['message']    =  null;
            }

            $check_pnl  = ("SELECT woonplaats 
                           FROM `locatie` 
                           WHERE    woonplaats='".$keyword."'");
            $check_pnl  = $check_pnl->num_rows;
            if($check_pnl == 0) {
                $response['message']    =  'Plaatsnaam Bestaat Niet';
            }else{
                // ECHO A FLAG TO SHOW THAT EVERYTHING WORKS FINE: ZERO ISSUE WAS FOUND
                $response['message']    =  null;
            }
        }
        die(json_encode($response));
    ?>

备注:

请注意, PHP脚本不应与HTML表单和JS保留在同一个文件中。否则,回显将反映在页面上。 将PHP移动到一个单独的文件以避免这种异常。

答案 1 :(得分:1)

您需要在代码中更改一些内容,例如:

  • 正如我在my comment中所说,您必须将您的AJAX请求发送到其他页面并在那里处理。因此,创建一个 check.php 页面来处理您的AJAX请求。
  • 不使用checkMailStatus()checkCityStatus()创建两个不同的函数,而只使用一个函数,例如checkStatus()函数来验证输入字段。
  • dataType设置添加到您的AJAX请求中,并将json对象作为来自服务器的响应发送。 dataType是您期望作为服务器响应的数据类型。
  • 使用prepared statements,它会阻止您的数据库遭受任何类型的SQL注入攻击。 See this SO Q/A

我认为 E-mailadres Woonplaats 都是必填字段。

因此,在 index.php 页面上, HTML jQuery 脚本应如下所示:

<强> HTML:

<form action="" onSubmit="return checkStatus(this);" method="post" id="registration">
    <input type="email" name="email" id="email" placeholder="E-mailadres" value="" required>
    <input type="text" name="keyword" id="keyword" placeholder="Woonplaats" value=""  required>
    <button type="submit" name="register" class="btn-red">Registreren!</button>
</form>

<强> jQuery的:

<script>
    function checkStatus(f){
        var email=$("#email").val();
        var keyword=$("#keyword").val();

        $.ajax({
            type:'post',
            url:'check.php',
            data:{email: email, keyword: keyword},
            dataType: 'json',
            success:function(data){
                if(data.status == "success"){
                    f.submit();
                }else{
                    alert(data.msg);
                }
            }
        });
        return false;
    }
</script>

check.php 页面上,处理您的AJAX请求,如下所示:

<?php

    // Your connection code
    $conn = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE_NAME");

    if(isset($_POST['email'], $_POST['keyword'])){
        $email = $_POST['email'];
        $keyword = $_POST['keyword'];

        $stmt = $conn->prepare("SELECT id FROM users WHERE email=?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        if($stmt->num_rows == 0){

            $stmt = $conn->prepare("SELECT woonplaats FROM `locatie` WHERE woonplaats=?");
            $stmt->bind_param("s", $keyword);
            $stmt->execute();
            $stmt->store_result();
            if($stmt->num_rows){
                echo json_encode(array('status' => 'success', 'msg' => 'no error'));
            }else{
                echo json_encode(array('status' => 'error', 'msg' => 'Place name does not exist'));
            }

        }else{
            echo json_encode(array('status' => 'error', 'msg' => 'Use a different email address'));
        }
    }else{
        echo json_encode(array('status' => 'error', 'msg' => 'missing fields'));
    }

?>

不要忘记 check.php 页面中更改此行$conn = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE_NAME");