1

Given the following table in the database:

create table products
(
    id    int auto_increment,
    item  char(20)       null,
    price decimal(10, 2) null,
    constraint table_name_pk
        primary key (id)
);

create unique index table_name_id_uindex
    on table_name (id);

When you run this code:

$sql = "SELECT price FROM products WHERE id = :item_id"
$values = [ 'item_id' => 100 ];
$stmt = $dbh->prepare($sql);
$stmt->execute($values);
$obj = $stmt->fetch(PDO::FETCH_OBJ);

The value of $obj->price will be a string instead of a float.

Is there any way to tell the PDO driver to cast this as a float?

Note: I understand that using PDO::FETCH_CLASS with a pre-defined object will do what I am asking. That's not what I want here. Making an entire class for each table that has dollar values in it is cumbersome, and requires a lot of work when the database changes (updating integration tests, etc...).

I also understand that this may be the desired behavior because float is a power of 2, and the MariaDB / MySQL data types are not. So, string may be the natural and best choice.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
DrDamnit
  • 4,736
  • 4
  • 23
  • 38
  • iirc MySQLi does your described behavior by default and PDO does not, MySQLi can opt-in to use native types, and PDO can opt-out of using native types. don't suppose you're using PDO::ATTR_STRINGIFY_FETCHES ? (which is the PDO way of opt-ing out of using native types) – hanshenrik Jun 23 '22 at 11:24
  • MySQL or mariaDB? Add the one you are using back into the tag list – RiggsFolly Jun 23 '22 at 11:26
  • ohhh right, maybe PDO doesn't trust "float" to be accurate enough to represent DECIMAL's (which is technically true). can you test `price DOUBLE null` ? – hanshenrik Jun 23 '22 at 11:27

0 Answers0