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

前端 未结 9 661
情话喂你
情话喂你 2020-12-31 03:26

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

9条回答
  •  鱼传尺愫
    2020-12-31 04:05

    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! :)

提交回复
热议问题