When data is returned from MySQL, it is automatically returned as strings, regardless of the MySQL data type.
Is there any way to tell MySQL/PHP to maintain the data types (e.g. int), so if you query an int column, you get an integer in PHP instead of a string?
$row is just a name of a variable. When you are using mysqli_fetch_array, you can get rows from resource you get from MySQL like while($row = mysqli_fetch_array($result)) { /* do_something */ }
In MySQL, INTEGER (INT) is a numeric value without a decimal. It defines whole numbers that can be stored in a field or column. In addition, MySQL supports the display_width attribute (for example, INT(1)) and the ZEROFILL attribute, which automatically adds zeros to the value depending on the display width.
TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
Well you can do Type casting to convert the type of returned data using PHP.
You can take a look at int
, intval
to convert to integers. You may also use settype
:
settype($foo, "array");
settype($foo, "bool");
settype($foo, "boolean");
settype($foo, "float");
settype($foo, "int");
settype($foo, "integer");
settype($foo, "null");
settype($foo, "object");
settype($foo, "string");
Another way would be:
$foo = (array)$foo;
$foo = (b)$foo; // from PHP 5.2.1
$foo = (binary)$foo; // from PHP 5.2.1
$foo = (bool)$foo;
$foo = (boolean)$foo;
$foo = (double)$foo;
$foo = (float)$foo;
$foo = (int)$foo;
$foo = (integer)$foo;
$foo = (object)$foo;
$foo = (real)$foo;
$foo = (string)$foo;
In MySQLi use bind_result
: it sets the correct type and handles NULL
.
If you are running Ubuntu:
sudo apt-get remove php5-mysql
sudo apt-get install php5-mysqlnd
sudo service apache2 restart
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With