如何从 MySQL 中获取整数作为 PHP 中的整数?

2021-12-25 00:00:00 types php mysql mysqli

当数据从 MySQL 返回时,无论 MySQL 数据类型如何,都会自动以字符串形式返回.

When data is returned from MySQL, it is automatically returned as strings, regardless of the MySQL data type.

有什么方法可以告诉 MySQL/PHP 维护数据类型(例如 int),因此如果您查询一个 int 列,您会在 PHP 中得到一个整数而不是字符串?

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?

推荐答案

好吧,你可以做类型转换 使用PHP转换返回数据的类型.

Well you can do Type casting to convert the type of returned data using PHP.

你可以看看intintval 转换为整数.你也可以使用 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");

另一种方式是:

$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;

相关文章