MySQL Integer Field Retrieval in PHP
When retrieving integer data from a MySQL database into PHP, it can be surprising to find that the returned value is a string instead. This article addresses this issue and provides a solution.
Problem:
Consider a MySQL table with a field:
userid INT(11)
Fetching this field with the following query:
SELECT userid FROM DB WHERE name='john'
and processing the result as:
$row=$result->fetch_assoc(); $id=$row['userid']; echo gettype($id); // Outputs: string
reveals that the value of $id is a string, not an integer.
Solution:
MySQL data types are always converted to strings when retrieved using PHP. To convert the string back to an integer, use one of the following methods:
$id = (int) $row['userid']; // Explicit typecasting $id = intval($row['userid']); // Using the intval() function
By employing either of these methods, you can ensure that your integer values are correctly interpreted and processed within your PHP script.
The above is the detailed content of Why Are MySQL Integer Fields Retrieved as Strings in PHP, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!