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

前端 未结 9 622
情话喂你
情话喂你 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:16

    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;
    
    0 讨论(0)
  • 2020-12-31 04:18

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

    $row['field'] = (int)$row['field'];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题