MySQL integer field is returned as string in PHP
Easiest Solution I found:
You can force json_encode to use actual numbers for values that look like numbers:
json_encode($data, JSON_NUMERIC_CHECK)
(since PHP 5.3.3).
Or you could just cast your ID to an int.
$row = $result->fetch_assoc();
$id = (int) $row['userid'];
When you select data from a MySQL database using PHP the datatype will always be converted to a string. You can convert it back to an integer using the following code:
$id = (int) $row['userid'];
Or by using the function intval()
:
$id = intval($row['userid']);
Use the mysqlnd (native driver) for php.
If you're on Ubuntu:
sudo apt-get install php5-mysqlnd
sudo service apache2 restart
If you're on Centos:
sudo yum install php-mysqlnd
sudo service httpd restart
The native driver returns integer types appropriately.
As @Jeroen has pointed out, this method will only work out-of-the-box for PDO.
As @LarsMoelleken has pointed out, this method will work with mysqli if you also set the MYSQLI_OPT_INT_AND_FLOAT_NATIVE option to true.
Example:
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);