Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an integer from MySQL as integer in PHP?

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?

like image 882
fbwb Avatar asked Feb 16 '11 09:02

fbwb


People also ask

What does $row mean in PHP?

$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 */ }

Is MySQL an integer?

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.

What is tiny INT in MySQL?

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.


3 Answers

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;
like image 139
Sarfraz Avatar answered Oct 27 '22 11:10

Sarfraz


In MySQLi use bind_result: it sets the correct type and handles NULL.

like image 26
aaz Avatar answered Oct 27 '22 10:10

aaz


If you are running Ubuntu:

sudo  apt-get remove php5-mysql
sudo  apt-get install php5-mysqlnd
sudo service apache2 restart
like image 27
Gaurav Gupta Avatar answered Oct 27 '22 11:10

Gaurav Gupta