Home >Backend Development >PHP Tutorial >Why Are MySQL Integer Fields Returned as Strings in PHP?
MySQL Integer Fields Returned as Strings in PHP
When retrieving data from a MySQL database using PHP, it's commonly observed that integer fields are returned as strings. This can be disconcerting, as one would expect an integer field to yield an integer value.
To understand this behavior, it's essential to note that PHP automatically converts all data retrieved from MySQL into strings. This conversion occurs regardless of the actual datatype in the database.
To circumvent this issue and obtain the correct integer value, there are two viable approaches:
$id = (int) $row['userid'];
$id = intval($row['userid']);
$stmt = $conn->prepare("SELECT userid FROM DB WHERE name='john'"); $stmt->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $id = $row['userid']; // Returns an integer
The above is the detailed content of Why Are MySQL Integer Fields Returned as Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!