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.