phpmysqltypesintgettype

MySQL integer field is returned as string in PHP


I have a table field in a MySQL database:

userid INT(11)

So I am calling it to my page with this query:

"SELECT userid FROM DB WHERE name='john'"

Then for handling the result I do:

$row=$result->fetch_assoc();

$id=$row['userid'];

Now if I do:

echo gettype($id);

I get a string. Shouldn't this be an integer?


Solution

  • When you select data from a MySQL database using PHP the datatype will always be converted to a string. You can convert it back to an integer using the following code:

    $id = (int) $row['userid'];

    Or by using the function intval():

    $id = intval($row['userid']);