Casting Issue in PHP PDO::FETCH_CLASS

user7784919

I'm tried to fetch the data from the State Table using PDO::FETCH_CLASS, but it returns the int field as string

MySQL Table Schema:

CREATE TABLE IF NOT EXISTS `INState` (
  `StateId` bigint(20) NOT NULL,
  `Name` varchar(255) NOT NULL
)

My PHP Code:

class StateModel
{
    public $StateId;
    public $Name;
}

$stateArr = $db->query('SELECT StateId, Name FROM INState')->fetchAll(PDO::FETCH_CLASS, 'StateModel');

var_dump($stateArr);

The Output of the above code is

array(2) { 
    [0]=> object(StateModel)#4 (2) 
        { ["StateId"]=> string(1) "1" ["Name"]=> string(14) "Andhra Pradesh" } 
    [1]=> object(StateModel)#5 (2) 
        { ["StateId"]=> string(1) "2" ["Name"]=> string(10) "Tamil Nadu" }
)

In Table Schema the column StateId is marked as bigint but the code side it returns as string. How to get the property StateId as int instead of string using PDO::FETCH_CLASS? Kindly assist me.

B.Balamanigandan

Off-course @Mayank is right, but we can explicitly set the properties datatype in the constructor.

class StateModel
{
    public $StateId;
    public $Name;

    public function __construct()
    {
        settype($this->StateId, 'integer');
    }
}

Finally the output of your code is

array(2) { 
    [0]=> object(StateModel)#1 (2) 
        { ["StateId"]=>  int(1) ["Name"]=> string(14) "Andhra Pradesh" } 
    [1]=> object(StateModel)#2 (2) 
        { ["StateId"]=>  int(2) ["Name"]=> string(10) "Tamil Nadu" }
)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related