Home >Database >Mysql Tutorial >Why are MySQL integers returned as strings in PDO, and how can I retrieve them as numbers?
Retrieving Numeric Types from MySQL with PDO
Problem:
When retrieving data from a MySQL database using PDO, integer values are returned as strings instead of their numeric type, even when the PDO class attribute PDO::ATTR_STRINGIFY_FETCHES is set to false.
Answer:
Understanding Numeric Type Issue:
It's common for databases to return numeric values as strings. This is because some database drivers, such as MySQL's default driver, treat all values as strings.
Preventing Stringification:
To prevent values from being returned as strings, the MySQL Native Driver (mysqlnd) must be used. This driver supports retrieving native data types, including numeric types.
Configuring mysqlnd:
To use mysqlnd, the following setting must be added to the PDO connection options array:
array( PDO::ATTR_EMULATE_PREPARES => false )
Example Code:
$dsn = 'mysql:host=localhost;dbname=my_db'; $user = 'root'; $pass = 'password'; $pdo = new PDO($dsn, $user, $pass, array( PDO::ATTR_EMULATE_PREPARES => false ));
By setting PDO::ATTR_EMULATE_PREPARES to false, prepared statement emulation will be turned off, allowing mysqlnd to retrieve numeric values as their correct data types.
The above is the detailed content of Why are MySQL integers returned as strings in PDO, and how can I retrieve them as numbers?. For more information, please follow other related articles on the PHP Chinese website!