MySQL Integer Field Returned as String in PHP
This issue arises when retrieving data from a MySQL database using PHP. Regardless of the datatype defined in the database, data is always returned as a string in PHP by default. This discrepancy can be puzzling, especially when expecting an integer field to behave as such.
In your specific case, with the database field userid declared as INT(11), the data is retrieved using the query:
"SELECT userid FROM DB WHERE name='john'"
To handle the result, you use:
$row=$result->fetch_assoc(); $id=$row['userid'];
However, when checking the datatype of $id using echo gettype($id);, it returns "string" instead of "integer".
Solution
To resolve this issue, PHP provides methods to convert the retrieved string data back to an integer format. You can use the following code:
$id = (int) $row['userid'];
Alternatively, you can also use the intval() function:
$id = intval($row['userid']);
By performing this conversion, you ensure that the $id variable is correctly recognized as an integer datatype, allowing for appropriate handling and operations as an integer.
The above is the detailed content of Why Is My MySQL Integer Field Returned as a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!