views:

311

answers:

2

When using mysql_fetch_assoc in PHP, how can I make it return the correct data types? Right now it appears to convert everything to strings, I'd prefer if it left the Ints as Ints, and somehow designated the Date/Time as either Object or somehow different than strings.

The reason for this is that I am using PHP as a backend to a Flex application, and Flex has some features such as automatically detecting return types, which don't work that well if everything comes in as a string.

A: 

You could build a mysql-specific layer around mdb2 that automatically detects field types using the SHOW COLUMNS command, but that would kind of defeat the purpose of using mdb2.

Keep in mind, also, that mysql suports integers well outside of PHP's range, (UNSIGNED BIGINT is 64 bits; PHP supports, at best, 64 bit signed ints, and less on 32 bit platforms) so automatically casting may be undesirable in some contexts. In those cases, you really want to keep the large ints in their string form, and manipulate them with bcmath

Frank Farmer
+11  A: 

I think a good strategy here is to programatically determine the datatype of each column in a table, and cast the returned results accordingly. This will allow you to interact with your database in a more consistent and simple manner while still giving you the control you need to have your variables storing the correct datatype.

One possible solution: You could use mysql_fetch_field() to get an object that holds meta-data about the table column and then cast your string back to the desired type.

//run query and get field information about the row in the table
$meta = mysql_fetch_field($result, $i);

//get the field tipe of the current column
$fieldType = $meta->type

A full example can be found here: http://us2.php.net/manual/en/function.mysql-fetch-field.php

Since PHP is loosely typed, you should have a relatively easy time with this.

If you are using OO techniques, you could create a class with this functionality in the setter() methods so you don't have to have duplicate code.

Robert Greiner