代码之家  ›  专栏  ›  技术社区  ›  TheOrdinaryGeek

Codeigniter和ajaxmysql错误处理

  •  0
  • TheOrdinaryGeek  · 技术社区  · 6 年前

    我(不熟悉)使用CI3,并创建了一个简单的表单,将插入一个值( age )进入MySQL数据库( test )桌子。我在表单中没有任何前端验证,我正在试验服务器端验证。

    这个 年龄

    • 数据类型:int
    • 允许非空:否
    • 默认:无默认

    (例如“john”),表单提交成功,但数据库将此值另存为 0 . 这是预期的行为吗?

    int

    我本以为会抛出以下错误;

    /*SQL错误(1054):“where子句”中的未知列“john”*/

    每当我尝试手动插入非int值(通过heidisql/phpmyadmin)时,就会出现这个错误(如预期的那样)。

    那么,如何在我的应用程序中检查这个错误,并采取相应的措施呢?

    我的代码如下;

    模型

    public function insert_form_data(){
        $data = array(
            'age'  => $this->input->post('age')
        );
        $result = $this->db->insert('test', $data);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        }
        else {
            return $this->db->error(); 
        }
    }
    

    public function insert_form_data(){
        $data = $this->Form_model->insert_form_data();
        echo json_encode($data);
    }
    

    查看

    <form name="myform" id="myform">
        <input name="age" type="text">
        <button type="submit" id="submit">Submit</button>
    </form>
    <p id="message"></p>
    
    
    $(document).ready(function() {
        $('#submit').on('click', function(event) {
            event.preventDefault();
            $.ajax({
                url: "form/insert_form_data",
                method: "post",
                data: $("#myform").serialize(),
                dataType: 'json',
                success: function(response) {
                    if (response == true) {
                        $('#message').text('Form submitted!');
                    }
                },
                error: function(response) {}
            });
            return false;
        });
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Sherif Salah    6 年前

    我不知道为什么你想要依赖sql错误,而你却在codeigniter的验证库中有了所有可能需要的东西,以便在插入之前进行检查,比如:

    public function insert_form_data()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('age', 'Age', 'required|integer');
        if ($this->form_validation->run() == FALSE)
        {
            $data['validation'] = validation_errors();
        }
        else
        {
            $data['validation'] = "Success";
        }
        $data["result"] = $this->Form_model->insert_form_data();
        echo json_encode($data);
    }