views:

228

answers:

1

I've tried fetching MySQL query results using mysql_fetch_row() mysql_result() and numeric values are being returned as strings. Is there any way to fetch the data as its datatype stored in the table?

The application will be querying many different queries so I will be unable to cast the values as the intended datatype on a 1 by 1 basis.

+2  A: 

I don't think getting data in their native datatypes (i.e. anything else that strings) can be done in PHP 5.2...

In PHP 5.3, it becomes possible, if I remember correctly, when you are using the new (new as in PHP >= 5.3) mysqlnd (MySQL Native Driver) driver.

After more digging through my bookmarks I found this article about mysqlnd : PDO_MYSQLND: The new features of PDO_MYSQL in PHP 5.3

It says this (quote) :

Advantages of using mysqlnd for PDO

mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally.

But this is PHP 5.3 only (provided your version of PHP 5.3 is compiled with mysqlnd (and not the old libmysql)), and seems to only be the case for prepared statements :-(

Which doesn't quite help, in your situation, I guess...


And here's another one, still about the new features of mysqlnd, which talks about this for not only prepared statements : PHP: New network traffic, CPU and memory savings with mysqlnd.

Not sure this has been merged into the official mysqlnd driver, though -- best way would be to try ; but it'll still be PHP >= 5.3 only, anyway...


Another solution would be to have, on the PHP-side, some kind of a mapping-system (like an ORM) to convert results coming from the DB to PHP datatypes...

And yes, this is bad if you want to use operators like === and !==, which are type-sensitive...

Pascal MARTIN
Thanks Pascal MARTIN! I've been googling for several hours and haven't found anything I could use. I'm relatively new to PHP, but it sounds like I'll need to go with PDO if I want the native support.Unfortunately my host is running 5.2.something...Also difficult, is that I'm trying to create an xml report file input that houses different query info. The PHP script reads the requested xml file and sends the queries off to the database, so I really won't ever know what data is being queried and how it should be returned.time to get creative I guess :)
redidas
PDO or not PDO should not change anything, in this case : what matters is the drivers used underneath *(i.e. libmysql vs mysqlnd)* -- and I'm not even sure that mysqlnd in PHP 5.3.2 does return native types for standard queries ;;; in your case, anyway, with PHP 5.2, the only solution you'll have would be some mapping layer, that does type conversions when needed...
Pascal MARTIN