Multi-responsibility model method in CodeIgniter is not performing in accordance with parameter type and quality rules
05:44 19 Oct 2015

I have a function which fetches the user details from the MySQL database. If the supplied function argument is an integer, the function treat it as a user id, if argument is an string it checks if string is a key in a predefined array, if the argument is a key in the array then it treats the argument as user_group id(fetched from config file), if the argument is string but not in the array keys, then it treats the argument as username, if none of the conditions are met it throws an error.

Problem : If I supply a username (string) to the function it works as it should. If I supply a string which is a key in the predefined array then it works. If I supply user id (int) it works for all ids but 1. That is, if $param is 1 it gives me 'Error 3' (below in the code) if supplied integer is anything else which is an id in the database then it works. The id 1 does exist in the database. The strange thing is that, the var_dump() actually dumps the correct data even if the supplied id is 1.

This is the last query string : SELECT * FROM user as u JOIN user_details as ud ON u.id = ud.id_user WHERE u.username = '1'

Clearly it's treating 1 as a string instead of integer. Why ? And why it is still fetching the first record (id=1) although it is treating the id as username u.username = '1'?

If I add $param = 1; at the start of the function _initialize ( $param ) then I get the following error.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 49 bytes) in E:\APACHE\htdocs\codeigniter\lib\system\database\DB_query_builder.php on line 2677

protected function _initialize ( $param )
{

    $this->ci->db->select (  '*'  );
    $this->ci->db->from ( $this->tableUser [ 'table' ] . ' as u' );
    $compare = NULL;

    if (  is_int ( $param )  ){
        $compare = $this->tableUser [ 'column' ] [ 'id' ];
    }
    elseif ( is_string ( $param ) && array_key_exists (  $param, $this->constantsServices  )  ){
        $compare = $this->tableUser [ 'column' ] [ 'id_user_groups' ];
        $param = $this->constantsServices [ $param ];
    }
    else if (  is_string ( $param )  ){
        $compare = $this->tableUser [ 'column' ] [ 'username' ];
    }else {
        throw new Exception ( 'Error 1' );
    }


    $this->ci->db->where ( 'u.' . $compare, $param );
    $this->ci->db->join (  $this->tableUserDetails [ 'table' ] . ' as ud', 'u.' . $this->tableUser [ 'column' ] [ 'id' ] . ' = ud.' . $this->tableUserDetails [ 'column' ] [ 'id_user' ]  );
    $query = $this->ci->db->get (  );

    if ( ! $query ){
        throw new Exception ( 'Error 2' );
    }

    $data = $query->unbuffered_row('array');

    var_dump ( $data );

    if ( !isset ( $data ) ){
        throw new Exception ( 'Error 3' );
    }
}
php mysql codeigniter codeigniter-3 query-builder