I have a table field in a MySQL database:
userid INT(11)
So I am calling it to my page with this query:
\"SELECT userid FR
You can do this with...
...depending on the extension you want to use. The first is not recommended because the mysql extension is deprecated. The third is still experimental.
The comments at these hyperlinks do a good job of explaining how to set your type from a plain old string to its original type in the database.
Some frameworks also abstract this (CodeIgniter provides $this->db->field_data()).
You could also do guesswork--like looping through your resulting rows and using is_numeric() on each. Something like:
foreach($result as &$row){
foreach($row as &$value){
if(is_numeric($value)){
$value = (int) $value;
}
}
}
This would turn anything that looks like a number into one...definitely not perfect.
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']);
I like Chad's answer, especially when the query results will be passed on to javascript in a browser. Javascript deals cleanly with numeric like entities as numbers but requires extra work to deal with numeric like entities as strings. i.e. must use parseInt or parseFloat on them.
Building on Chad's solution I use this and it is often exactly what I need and creates structures that can be JSON encoded for easy dealing with in javascript.
while ($row = $result->fetch_assoc()) {
// convert numeric looking things to numbers for javascript
foreach ($row as &$val) {
if (is_numeric($val))
$val = $val + 0;
}
}
Adding a numeric string to 0 produces a numeric type in PHP and correctly identifies the type so floating point numbers will not be truncated into integers.
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.
Edit:
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 = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);
In my case mysqlnd.so
extension had been installed. BUT i hadn't pdo_mysqlnd.so
. So, the problem had been solved by replacing pdo_mysql.so
with pdo_mysqlnd.so
.
This happens when PDO::ATTR_EMULATE_PREPARES
is set to true
on the connection.
Careful though, setting it to false
disallows the use of parameters more than once. I believe it also affects the quality of the error messages coming back.