This is a feature I have run into a few times (specifically when writing the unit tests for the Mysql Package). I thought I would post my thoughts and hopefully others will be able to expand on the topic.
When querying data out of MySQL into PHP, all values arrive in PHP as strings, even if the MySQL column type is INT. This is documented behavior:
PHP Manual – mysql_fetch_array…
Returns an array of strings that corresponds to the fetched row…
I understand that PHP is a loosely typed language, which means PHP will convert the string to an integer on the fly (if it is deemed appropriate); but my question is: Why do integers arrive in PHP as strings?
A little research into the topic shows that the integer to string conversion actually happens outside the scope of PHP and lies in the MySQL C API. The mysql_fetch_row() function (within the C API) returns the data type MYSQL_ROW, which is defined as:
A type-safe representation of one row of data. It is currently implemented as an array of counted byte strings. (You cannot treat these as null-terminated strings if field values may contain binary data, because such values may contain null bytes internally.) Rows are obtained by calling mysql_fetch_row().
I have asked in a few forums and chat rooms about this, but was never really able to get a definitive answer. Most people say that since PHP is loosely typed it doesn’t matter, which I cannot accept as an answer, especially since the MySQL C API is not used exclusively for loosely typed languages.
One theory I heard is that since the C API is used in many different languages for connecting to MySQL, the creators decided it would simply be easier to return all values as strings. This could possibly be the case, but I do not know of a common language which could not handle an integer.
Has anyone else looked into this topic before, or do you have the answer that has eluded me?



PDF













