Welcome Guest, Not a member yet? Register   Sign In
MySQL int fields -> php strings
#1

[eluser]michaelUFL[/eluser]
SUMMARY

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

CONFIG

php 5.3.2
MySQL 5.1.49
CI_VERSION 1.7.2

DETAIL


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:

http://www.webmasterworld.com/php/3618311.htm


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?


Thanks,
Michael
#2

[eluser]michaelUFL[/eluser]
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]

Michael

----

$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);
var_dump($object);
echo json_encode($object);

-->

object(stdClass)#1 (3) {
["intField"]=>
string(1) "1"
["two"]=>
string(1) "2"
["count"]=>
string(1) "1"
}
{"intField":"1","two":"2","count":"1"}
#3

[eluser]danmontgomery[/eluser]
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 php.net.

I would do something like:

Code:
$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);
    }
}




Theme © iAndrew 2016 - Forum software by © MyBB