简体   繁体   English

提交表单后如何检查数据库中存在的文本框值

[英]How to check the text box value that exist in the database after submit the form

I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not. 我有此HTML代码的形式,我想检查用户输入的值在数据库中是否已经存在。

<tr height="50">
    <td valign="top"><label for="CINumber"><span style="color:red">*</span>CI Name:</label></td>
     <td><input type="text" id="CINumber" name="CINumber"></td>                     
</tr>

I have this ``JavaScript function for sumbmit the form values: 我有这个``JavaScript函数用于汇总表单值:

function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);                                                              
            if(status == "success"){                            
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");                              
            } else {
                alert("CI Name is already present!");
                return ;
            }   
        },                              
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });                                                                         
}

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url.. 然后在“ PHPMethodCalls_AL.php” URL中调用PHPMethod调用。

if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}

After that I call the PHP function that connect with the database. 之后,我调用与数据库连接的PHP函数。

function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){   
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){                     
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);                    
        }
        else {  
            echo "!success";
        }
    }                                                       
}

After click submit, I only got the (status == "success") then pop up 2 alert box even the data is already exist in the database. 单击提交后,我只得到了(状态==“成功”),然后弹出2个警告框,即使数据库中已经存在数据。 However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. 但是,重复值未保存在数据库中,因为我为此字段设置了UNIQUE。 Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"... 请建议我,如果数据已存在,我应该如何获取正确的警报框,如果不存在,则显示“ Alredy exist”(如果存在,则显示“ Alredy存在”)...

Change following code ... 更改以下代码...

                            url: 'PHPMethodCalls_AL.php',
                            type: 'post',
                            data: {'action':'AddNewCI', 'cNumber' : cNumber },

                            success: function(data) {

                            if(data == "success"){                            
                                alert("CI Name can be assigned");
                                alert("Successfully Register New CI Record.");                              
                            }

no need to use json_encode , you can directly echo any value if you want. 无需使用json_encode,您可以根据需要直接回显任何值。

if($_POST['action'] == "AddNewCI"){
$cNumber = $_POST['cNumber'];
$newCI = AddNewCI($cNumber);
echo $newCI;
}

change you function return value... 更改函数的返回值...

function AddNewCI($cNumber){
    global $DB;

        if(!empty($cNumber)){   

            $namequery="SELECT Name from Item where Name='$cNumber'";
            $namecheck=mysql_query($namequery);
            $row=mysql_num_rows($namecheck);
        if($row==0){                     
                $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
                $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__); 
                return "success";                   
            }
        else
            {   
                 return "error";
            }

        }                                                       
   }

Change your success function with this in ajax request : 在ajax请求中更改您的成功功能:

success:fucntion(data){
  if(data=="success"){
    alert("Your success message here.");
  }else{
    alert("Alert message whatever you want.");
  }
},

try this one less code and working well 少尝试这段代码,效果很好
here no need to display error message if you use jquery validation you can simply use "render" and render function displayed error message like required in jquery // When the browser is ready... $(function() { // Setup form validation on the #register-form element $("#addfrm").validate({ 如果您使用jquery验证,这里不需要显示错误消息,您可以简单地使用“ render”并呈现显示的错误消息,如jquery中所要求的// //浏览器准备好... $(function(){//设置表单验证在#register-form元素$(“#addfrm”)。validate({

   // Specify the validation rules
    rules: {
      CINumber: {
            required: true,
            remote: {
            url: "PHPMethodCalls_AL.php",
            type: "post",
            data: {
              CINumber: function() {
                return $( "#CINumber" ).val();
              }
            }
          }
        }
    },

    // Specify the validation error messages
    messages: {
        CINumber: {
            required: "Please enter your CINumber",
            remote:"Entered CINumber already exists please enter another one"
       }
    },

    submitHandler: function(form) {
        form.submit();
    }
});
});
</script>

 PHPMethodCalls_AL.php
   this file return true when cinumber not exits on database and when it`s return false that means cinumber already exits on database      


<?php
   //add database configuration 
   $CINumber=$_POST['CINumber'];
   $query="SELECT * FROM `table_name` where `CINumber`=$CINumber";
   $result=mysql_query($query);
   $number_of_rows = mysql_num_rows($result);
   if($number_of_rows){
      echo "false";
   }else{
     echo "true";
   }
   die();
   ?>

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

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