CodeIgniter Forums
How to catch database operation errors - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forum-10.html)
+--- Thread: How to catch database operation errors (/thread-74836.html)



How to catch database operation errors - _Alain_ - 11-13-2019

Hi

I try to catch an error if something with the database operations goes wrong.
I tried many variants of the following code but $data always returns true (it doesn't matter if the database operation produces an error or not).

What do I have to do to catch an error if database operation went wrong?

Model
PHP Code:
<?php
class Users_model extends CI_Model {
    public function deleteUser($userID)
    {
        
$this->db->where('id'$userID);
        
$result $this->db->delete('users');
        return 
$result;


Controller
PHP Code:
<?php
class Users extends CI_Controller {

    function 
__construct()
    {
        
parent::__construct();
        
$this->load->model('users_model');
    }

    public  function deleteUser()
    {
        
$userID $this->input->post('user_id');
        $data $this->users_model->deleteUser($userID);
        echo 
json_encode($data);
    }



View (see the "<" for var user_id. This should generate an error because the user with such an id cannot be found)
PHP Code:
            // Delete user button
            $('.btn-delete-user').on('click', function(){
                var user_id                "<" + $(this).data("id");
                $.ajax({
                    type "POST",
                    url  "<?php echo site_url('users/deleteUser')?>",
                    dataType "JSON",
                    data : {user_id:user_id},
                    success: function(data){
                        loadUsers();
                    },
                    error : function() {
                        alert("Some error happened");
                    }
                });
                return false;
            }); 

Kind regards
Alain


RE: How to catch database operation errors - jreklund - 11-14-2019

You will need to check in your PHP code, in case it's true or false.
If it's false you will need to send a different status header.

https://codeigniter.com/user_guide/libraries/output.html#CI_Output::set_status_header

jQuery will give you success on all 200 requests. And that's the default status header.


RE: How to catch database operation errors - loopzzz - 11-15-2019

@jreklund is right,
i must add that API CONTROLLER has to handle the error processing, also please read on and implement correct REST API responses and http response codes, and JQUERY knows how to handle them

what i would do is to check the result of the DB queries in the CONTROLLER and then return corresponding http headers and the payload (null, false, or nothting {}). then JQUERY can detect and handle the appropriate action.


RE: How to catch database operation errors - _Alain_ - 11-15-2019

I think I'm strugling over some basic missunderstanding.

The following, in my case, always returns true. Even it was not able to delete it.
But why?
From my point of view it should only return true if the record has been deleted.

PHP Code:
$result $this->db->delete('users'); 



RE: How to catch database operation errors - _Alain_ - 11-15-2019

Ok I did now this:
PHP Code:
$result $this->db->where('id'$userID); 

Instead of this:
PHP Code:
$result $this->db->delete('users'); 

The first one returns the following.
But I can't find any error there (I compared it with a correct query and with a query that should fail, but both return the same):
Code:
dbdriver: "mysqli", compress: false, delete_hack: true, stricton: false, dsn: "", username: "root",…}
CACHE: null
benchmark: 0.0005290508270263672
bind_marker: "?"
cache_autodel: false
cache_on: false
cachedir: ""
char_set: "utf8"
compress: false
conn_id: {affected_rows: null, client_info: null, client_version: null, connect_errno: null,…}
affected_rows: null
client_info: null
client_version: null
connect_errno: null
connect_error: null
errno: null
error: null
error_list: null
field_count: null
host_info: null
info: null
insert_id: null
protocol_version: null
server_info: null
server_version: null
sqlstate: null
stat: null
thread_id: null
warning_count: null
data_cache: []
database: "ci_test"
db_debug: false
dbcollat: "utf8_general_ci"
dbdriver: "mysqli"
dbprefix: ""
delete_hack: true
dsn: ""
encrypt: false
failover: []
hostname: "localhost"
password: ""
pconnect: false
port: null
queries: ["DELETE FROM `users`↵WHERE `id` = '<29'"]
0: "DELETE FROM `users`↵WHERE `id` = '<29'"
query_count: 1
query_times: [0.0005290508270263672]
0: 0.0005290508270263672
result_id: true
save_queries: true
stricton: false
subdriver: null
swap_pre: ""
trans_enabled: true
trans_strict: true
username: "root"


The second one always returns true.


RE: How to catch database operation errors - jreklund - 11-15-2019

So what type of things are it failing on? It should only return FALSE if it couldn't delete a existing entry.


RE: How to catch database operation errors - _Alain_ - 11-19-2019

(11-15-2019, 11:29 AM)jreklund Wrote: So what type of things are it failing on? It should only return FALSE if it couldn't delete a existing entry.

Yes, it should only return FALSE if it couldn't delete a existing entry. Else it should return TRUE.


RE: How to catch database operation errors - InsiteFX - 11-19-2019

PHP Code:
$error $this->db->error(); // Has keys 'code' and 'message' 



RE: How to catch database operation errors - _Alain_ - 11-20-2019

I extended the model as followed for testing purpose:
PHP Code:
        $this->db->where('id'$userID);
        
$error $this->db->error();
        echo 
json_encode($error); die;

        
$this->db->delete('users'); 


But it always returns no error. Even if I put error() after db-delete.
The response in Developer Tools is:
Code:
{"code":0,"message":""}