How can I get the correct data types from MySQL with PDO?

my PDO fetch returns everything as a string.

I have a custom class with id (int) and username (varchar).

When trying to execute the following sql query

$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), id is a string. How can I do this, so PDO respects the correct data types from mysql?

+7
source share
1 answer

You can use another fetch_style . If you have a custom class, you can force the PDO to return an instance of the User class with

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

Now you can take care of checking the properties and casting in the User class where it belongs.

Connected:

+3
source

All Articles