2017-06-01 46 views
1

我面臨檢查數據庫中唯一電話號碼的問題。在提交時,它會檢測我輸入的每個數字作爲數據庫中發現的數字,即使它不存在。附接下面的代碼:Codeigniter:ajax中的唯一電話號碼檢查

AJAX

<script> 
function checkdata(){ 
var tel = $('.tel').val();  
var x; 
if(tel){ 
$.ajax({ 
    url: '<?php echo base_url('index.php/admin/customer/check_phone_availibility1'); ?>', 
    data:{tel:tel}, 
    error: function() { 
    alert("An error has occurred."); 
    }, 
    success: function(data) { 
    x= data; 

    }, 
    type: 'POST' 
}); 
if(!x){ 
alert('This phone exists in database'); 
$('.tel').val(""); 
return false; 
} 
} 
} 
</script> 

控制器

public function check_phone_availibility1(){ 
$tel = $this->input->post('tel'); 
$success = $this->customer_m->check_phone_no_availability($tel); 
if($success){ 
    echo true; 
} 
else { 
    echo false; 
} 
} 

MODEL

public function check_phone_no_availability($phone){ 
$query = $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
$phone = $query->result(); 

if(count($phone)) 
{ 
    return false; 
} 
else 
{ 
    return true; 
}  

} 

VIEW

<input type="text" name="phone" value="" class="form-control tel" id="phone" maxlength="10" required=""> 
<input type="submit" name="submit_btn" value="Save Customer" class="btn btn-success" onclick="return checkdata();"> 

我將非常感激,如果這個問題能夠得到解決。由於

+1

嘗試'如果(計數($電話)> 0)' – hungrykoala

+0

嘿,我會努力它出來回覆你 –

回答

0
$var = false; 
$var2 = ''; 
$var3 = null; 

產生

count($var) => 1 
count($var) => 1 
count($var) => 0 

所以,在你的模型,你可以檢查你的查詢產生的任何結果,你可以做這樣的事情:

$query = $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
$query_result= $query->result(); 

return (count($query_result) > 1) ? true : false; 

,或者只是

return ($query_result) ? true : false; 
+0

嗨,謝謝你的回覆,我會給它一個去 –

+0

對不起基思,它沒有解決問題 –

0

試試這個有些修改離子:

控制器

public function check_phone_availibility1(){ 
$tel = $this->input->post('tel'); 
$success = $this->customer_m->check_phone_no_availability($tel); 
if($success->num_rows() == 0){ 
    echo 1; 
} 
else { 
    echo 0; 
} 
} 

模型

public function check_phone_no_availability($phone){ 
return $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
} 

AJAX

<script> 
function checkdata(){ 
var tel = $('.tel').val();  
var x; 
if(tel){ 
$.ajax({ url: '<?php echo base_url('index.php/admin/customer/check_phone_availibility1'); ?>', 
data:{tel:tel}, 
error: function() { 
alert("An error has occurred."); 
}, 
success: function(data) { 
x= data; 

}, 
type: 'POST' 
}); 
if(x != "1"){ 
alert('This phone exists in database'); 
$('.tel').val(""); 
return false; 
} 
} 
} 
</script> 
+0

感謝您的答覆,我會嘗試上面的代碼 –

+0

@davidnoronha您的代碼工作好? –

+0

即使在添加新號碼的情況下,它仍然顯示電話號碼 –

0
if(count($phone) > 0) 
{ 
    return false; 
} 
else 
{ 
    return true; 
} 

你需要檢查,如果回報率大於0,因爲如果將返回true,如果該值不爲空或假

+0

它不提交,但即使該號碼不存在,它仍會顯示「電話號碼存在於數據庫中」 –