CodeIgniter Forums
MySQL int fields -> php strings - Printable Version

+- CodeIgniter Forums (
+-- Forum: Archived Discussions (
+--- Forum: Archived General Discussion (
+--- Thread: MySQL int fields -> php strings (/thread-34040.html)

MySQL int fields -> php strings - El Forum - 09-16-2010


int fields fetched from MySQL get returned to php as string values


php 5.3.2
MySQL 5.1.49


I have searched through FAQ + SQL FAQ + forums and did not see any references to the problem I am having.

* I am fetching records from a MySQL database.

* some fields of the records are of type int and smallint

* the fields are showing up in php as string fields

* this is a problem for me because I am using json_encode to transfer to JavaScript and the problem gets replicated/transferred

I googled and found a reference to someone else having the same problem a few years ago:

I would rather find a general solution to this problem rather than hack it on a case-by-case basis.

It seems to me that this is a database connector issue ...

Q: What/who manages the database connector for CI & MySQL?

Q: Any other advice for me?


MySQL int fields -> php strings - El Forum - 09-16-2010

Further investigation leads me to believe that this is not a codeigniter issue.

Using the MySQL connector directly gives the same results ... see below.

I have posted a message to [email protected]



$sql = 'SELECT intField, 1+1 AS two, COUNT(*) AS count FROM testtable
WHERE intField=1';

$query_results = mysql_query($sql);
$object = mysql_fetch_object($query_results);
echo json_encode($object);


object(stdClass)#1 (3) {
string(1) "1"
string(1) "2"
string(1) "1"

MySQL int fields -> php strings - El Forum - 09-16-2010

PHP's mysql_fetch_assoc and mysql_fetch_object functions return only strings, this is clearly explained both on the page you linked to and the pages for these functions on

I would do something like:

$query = $this->db->query('some query');
if($query && $query->num_rows()) {
    foreach($query->result_array() as $row) {
        // Replace integer strings with actual integers
        array_walk($row, create_function('&$val','$val = ( is_numeric($val) ? intval($val) : $val );'));

        // Do whatever you need to do
        $data[] = json_encode($row);