How to get an integer from MySQL as integer in PHP

2019-02-06 05:03发布

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?

9条回答
Evening l夕情丶
2楼-- · 2019-02-06 05:36

If you are running Ubuntu:

sudo  apt-get remove php5-mysql
sudo  apt-get install php5-mysqlnd
sudo service apache2 restart
查看更多
Juvenile、少年°
3楼-- · 2019-02-06 05:39

I don't know in what context you asked this question. Because the data type of a php variable is dependent on what data type a column in your table has. If the column has data type "int" in mysql, you get an integer in php (not a string).

But anyways, you can use either is_numeric(), is_int() or gettype() php functions to know the data type of a returned value from Mysql. The problem with is_numeric() is that it returns true even if a variable contains a numeric string e.g. "2". But gettype() will return "string" and is_int() will always return false in the example mentioned i.e. "2".

Once you know the data type of a returned value you can bind the php variable to maintain that type by type casting like this:

// Suppose this is the returned value from mysql and
// you do not know its data type.
$foo = "2";

if (gettype($foo) == "string"){
    $foo = (string) $foo;
}

You can make several checks for what data type the variable has and then cast it accordingly.

I hope this reply would be helpful. Good luck! :)

查看更多
对你真心纯属浪费
4楼-- · 2019-02-06 05:41

You could use type casting once you've pulled the data from your MySQL database

$row['field'] = (int)$row['field'];
查看更多
Luminary・发光体
5楼-- · 2019-02-06 05:47

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

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-06 05:47

As PHP isn't a strongly typed language, this is somewhat meaningless, but you could of course simply cast the field in question to an int via settype, etc. prior to usage.

Irrespective, there's no way (that I know of) to maintain this "type" information automatically.

查看更多
做自己的国王
7楼-- · 2019-02-06 05:47

If you want to get the values ordening by Price, you can change the Data Type to FLOAT from column (ex: price)

EX:

TABLE eletronics

price        id
----------------
55.90        1
40.33        2
10.60        3
1596.90      4
56.90        5

PHP:

$sql = $pdo->query("SELECT * FROM eletronics ORDER BY price DESC");

//result

1596.90      4
56.90        5
55.90        1
40.33        2
10.60        3

//The order is being per prices //OBS: You can change the dots with "," using the str_replace() //result: 1596,90 - 56,90 - 55,90 - 40,33 - 10,60 etc.

查看更多
登录 后发表回答