-1

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.

  • [related answer](https://stackoverflow.com/a/1197424/6337519). Had the same issue as you, worked fine for me (php7) – joH1 Oct 08 '17 at 19:57

2 Answers2

1

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" }
)
B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130
0

When you select data from a MySQL database using PHP the datatype will always be converted to a string. You can check every PDO Fetch method return type is mixed. You can convert it back to an integer using the following code:

$id = (int) $row['column'];

Or by using the function intval():

$id = intval($row['column']);
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • Is there is any optional setting to do this casting? otherwise the proposed solution needs to iterate the collection once again. –  Jun 17 '17 at 03:41
  • If you want to just display it, than there is no need to convert it. And if you want to do some calculation than you have to iterate it. – Mayank Pandeyz Jun 17 '17 at 03:43
  • Some times I fetch some data and do some operation. Moreover I'm sending this to the angular UI app, there again an issue. So I asked by default if its return the int means no issue otherwise I will do it manually. Thanks for your kind information. –  Jun 17 '17 at 03:50
  • In angular app, we need to do sorting if the int is coming as string means sorting won't give the proper result. –  Jun 17 '17 at 03:52
  • In that case u have to iterate it. If I am not wrong, you have to iterate the result set as well to show each record, type cast at that time – Mayank Pandeyz Jun 17 '17 at 03:55