aviv
aviv

Reputation: 2809

php selecting from mysql and receiving th data types

When selecting from a MySQL table in PHP the results are always strings. Is there a way to get the correct datatype already?

Consider my table:

 CREATE TABLE bar(
     id    INT,
     price FLOAT,
     name  VARCHAR(40));

Now what i have to do is:

   $result = mysql_query("SELECT id,price,name FROM bar");
   while($row = mysql_fetch_assoc($result))
   { 
      $row['id'] = (int)$row['id'];
      $row['price'] = (double)$row['price'];
   }
   mysql_free_result($result);

Is there a way to get the data-types correctly from the query transparently?

10x, Aviv

Upvotes: 3

Views: 1323

Answers (3)

LGT
LGT

Reputation: 5034

This is not an answer to the question, but rather a way (hack?) around the issue.

CREATE TABLE bar(
    int_id       INT,
    float_price  FLOAT,
    varchar_name VARCHAR(40)
);

Then, as you retrieve everything, loop through the column/key names and process them according to type (everything before the first underscore) and column name (everything after the first underscore).

Also, this requires you to edit the tables.. which could be problematic.

Upvotes: 0

zerkms
zerkms

Reputation: 254896

No, all data that comes from mysql is a string actually and you cannot do anything with it.

Upvotes: 2

sharpner
sharpner

Reputation: 3937

actually no, the only thing you can do is to check for datatypes,

pseudo:

if(is_int())
    (int)....
else if(is_float())
    (float)...
else ...

and check for all the types you are expecting... as a last resort it's always string.

but if you would use PDO you could get the dataTypes for the column and convert accordingly...

see: List of PHP native_type's for PDO getColumnMeta()

Upvotes: 0

Related Questions