Thursday, April 25, 2019

Codeigniter: check mysql connection

To check error in mysql connection, we need to change ENVIRONMENT to Production. Here is the example:
    //define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
    //define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing');
    define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');
There are two ways to catch error in our controller:
1. Using dblib
        $this->load->dbutil();
        if ($this->dbutil->database_exists('myca')) {
            // Connection ok
        } else {
            // Connection fail
        }
2. Checking error in db
        $this->load->database();
        $errhandle = $this->db->error();
        if ($errhandle['code']==0) {
            // Connection ok
        } else {
            // Connection fail
            // to dump error code var_dump( $this->db->error());
        }
Tested on PHP 7.2 and Codigniter 3.1.10

No comments:

Post a Comment