Last Updated: February 25, 2016
·
7.331K
· pix-art

How to stop Doctrine from turning integer into string

In our project we use native MySQL queries to fetch our data. This way we can skip the heavy ORM part but this made us run into an annoying issue. When ever we did a select that should return an integer it was transformed into a string.

Example:

Database

position    int(11)

Query

$sql = "SELECT g.position FROM goal g";
$stmt = $this->conn->executeQuery($sql);
var_dump($stmt->fetchAll());

Response

array (size=2)
  0 => 
    array (size=3)
      'position' => string '2' (length=1)
  1 => 
    array (size=3)
      'position' => string '1' (length=1)

So you can see our query did return the all the positions we found but they were all transformed into strings although we have them declared as Integers.

How can we fix this?

STEP 1: Install the MySQL Native Driver and remove the old one

sudo apt-get remove php5-mysql
sudo apt-get install php5-mysqlnd

STEP 2: Change option 20 in your doctrine settings

In doctrine

$params = array(
    'driver' => 'pdo_mysql',
    'dbname' => 'mydb',
    'host' => 'localhost',
    'user' => 'root',
    'password' => '',
    'charset' => 'utf8',
    'driverOptions' => array(
        PDO::ATTR_EMULATE_PREPARES => FALSE
    )
);

In symfony

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   "%database_driver%"
                host:     "%database_host%"
                port:     "%database_port%"
                dbname:   "%database_name%"
                user:     "%database_user%"
                password: "%database_password%"
                charset:  UTF8
                options:
                    20: false

More info

20 = PDO::ATTR_EMULATE_PREPARES

http://php.net/manual/en/pdo.setattribute.php

New response

array (size=2)
  0 => 
    array (size=3)
      'position' => int 2
  1 => 
    array (size=3)
      'position' => int 1

Enjoy!

Extra thanks: @wmolenberghs

All my tips have been moved to my blog www.pix-art.be so come check it out!