How can I fetch correct datatypes from MySQL with PDO?

mysql, pdo, php

Solution

You could use a different fetch_style. If you have a User class, you could force PDO to return a instance of the User class with

$statement->fetchAll(PDO::FETCH_CLASS, "User");

You can now take care of properties validations and casting inside the User class, where it belongs.

Related:

- PHP PDO: Fetching data as objects - properties assigned BEFORE __construct is called. Is this correct?

- PDO PHP Fetch Class

Problem

my PDO fetch returns everything as a string. I have a user class with id (int) and username (varchar). When I try the following sql request ``` $db->prepare('SELECT * FROM users WHERE id=:id_user'); $db->bindParam(':id_user', $id_user); $db->execute(); $user_data = $db->fetch(PDO::FETCH_ASSOC); ``` and var_dump($user_data), the id parameter is a string. How can I make it so PDO respects the correct datatypes from mysql ?

Original source

Related problems