2015-06-04 100 views
2

我正在使用Codeigniter,並且在通過ajax在數據庫中插入值時遇到問題。 當sql查詢拋出錯誤時,會發生問題。 這是我的控制器代碼: -Jquery Ajax當sql返回錯誤時顯示錯誤500

public function Register_data() 
{ 
    $data = array(
     'user_name'=>$this->input->post('name'), 
     'user_email'=>$this->input->post('emailid'), 
     'user_pwd'=>$this->input->post('pwd'), 
     'user_pno'=>$this->input->post('pno'), 
     'user_gender'=>$this->input->post('gender'), 
     'user_age'=>$this->input->post('age'), 
     'dor'=>date('Y-m-d H:i:s'),); 
    $this->load->model('Register'); 
    $this->Register->insert_content($data); 
    $output = array(); //Creating output array for json response to ajax 
    $output['result'] = $this->Register->getStatus(); echo $output['result'].'---'; 
    $output['message'] = $this->Register->getMessage(); echo $output['message']; 
    echo json_encode($output); 
} 

我的模型代碼是這樣: -

class Register extends CI_Model{ 
var $message; 
var $status; 
public function __construct() 
{ 
    parent::__construct(); 
    $this->load->database(); 
} 
public function insert_content($da) 
{ 
    if ($this->db->insert('user',$da))//Checking if mysql query is successful 
    { 
     $this->status = true; 
     $this->message = "DATA INSERTED"; 
    } 
    else 
    { 
     $this->status = false; 
     $this->message = $this->db->error_message();    
    } 
} 
public function getStatus() 
{ 
    return $this->status; 
} 
public function getMessage() 
{ 
    return $this->message; 
}} 

,這是我的Ajax調用: -

$.ajax({ 
    url: "<?php echo site_url('Home_Controller/Register_data');?>", 
    data: $("#frm").serialize(), 
    type: 'POST', 
    success: function (data) { 
     alert(data); 
     var resp = $.parseJSON(data); 
     if (resp.result) { 
      window.location.href = "<?php echo site_url('Home_Controller');?>"; 
     } else { 
      $("#msgs").html(resp.message); 
     } 
    }, 
    error: function (error) { 
     $("#msgs").html(JSON.stringify(error)); //This is returned when model condition for inserting data throws error. 
    } 
}); 

Red Color text is an error which is displayed when sql duplication occurs

而且請注意數據正在被插入。因此插入時沒有問題。我用json作爲對Ajax的響應返回。只有在插入錯誤時纔會出現問題。例如: - 我把電子郵件保存爲數據庫中唯一的,因此當我在數據庫中插入重複,然後mysql會拋出一個錯誤,說重複錯誤,因爲你可以看到我的代碼模型中,我已經插入代碼,如果條件和插入查詢獲取失敗狀態並將消息存儲在變量中。這是我以前在覈心php中所做的。我不知道如何在codeigniter中處理這個問題。請提供一個很好的解決方案。任何幫助將不勝感激。

+0

檢查此鏈接...它可以幫助你http://stackoverflow.com/questions/1893381/codeigniter-continue-on-sql-error – Ashwani

+0

Thanx Ashwani,因爲你的帖子我已經解決了這個問題 –

回答

0

Codeigniter包含error()函數以顯示db錯誤。 db-> error_message()是聽到的問題