CodeIgniter returns all fields as strings
A proper way to solve this issue is to set mysqli option in the Codeigniter driver.The below method is for who using mysqli as database driver.
Method 1:
Enable mysqlnd driver in your php extention. This will mostly solve your problem. If this not, then try method 2
Method 2 (May not work in all systems):
- Open mysqli_driver.php file from system > database > drivers > mysqli_driver.php
- Add below line to the code
Code:
public function db_connect($persistent = FALSE) ... $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); // already exits $this->_mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE,TRUE); // add this line ...
After the code change, you get response like below
array (size=16) 'auth_id' => int 1 'role' => string 'admin' (length=5) 'permissions' => string 'all' (length=3) 'login_attempt' => int 0 'active' => int 1 'mobile_verified' => int 1
This can be achieved using PDO driver. Then setting PDO::ATTR_EMULATE_PREPARES to false. This can be done in database.php. I believe using options array is undocumented feature.
Change application/config/database.php to use PDO and add PDO::ATTR_EMULATE_PREPARES to options:
$db['default'] = array( 'dsn' => 'mysql:host=localhost;dbname={{my_db}};charset=utf8;', 'username' => 'my_db_user', 'password' => '123', 'database' => 'my_db', 'dbdriver' => 'pdo', 'options' => [ PDO::ATTR_EMULATE_PREPARES => false, ], ... );
Now you should have all the data returned from the DB with correct types.
If you don't want to change your system driver you can change your application/Core/MY_Controller.php.
Mixing Kalaivanan and Firze answers but using mysqli, not PDO.
Note: Decimals are still converted to string in pdo and also in mysqli, so use Double instead.
Create/change application/Core/MY_Controller.php as follows:
class MY_Controller extends CI_Controller{ public function __construct() { parent::__construct(); $this->db->conn_id->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true); }}
WARNING: If you use BIT columns they won't work, they will always return zeros. Because a bug on driver. See: mysqlnd with MYSQLI_OPT_INT_AND_FLOAT_NATIVE fails to interpret bit columns.