Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch correct datatypes from MySQL with PDO? [duplicate]

Tags:

php

mysql

pdo

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 ?

like image 959
Lukmo Avatar asked Feb 20 '13 10:02

Lukmo


1 Answers

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
like image 163
Jose Armesto Avatar answered Oct 10 '22 02:10

Jose Armesto