MySQL integer field is returned as string in PHP

前端 未结 15 2457
南旧
南旧 2020-11-22 16:17

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 FR         


        
15条回答
  •  猫巷女王i
    2020-11-22 16:52

    I like Chad's answer, especially when the query results will be passed on to javascript in a browser. Javascript deals cleanly with numeric like entities as numbers but requires extra work to deal with numeric like entities as strings. i.e. must use parseInt or parseFloat on them.

    Building on Chad's solution I use this and it is often exactly what I need and creates structures that can be JSON encoded for easy dealing with in javascript.

    while ($row = $result->fetch_assoc()) {
        // convert numeric looking things to numbers for javascript
        foreach ($row as &$val) {
            if (is_numeric($val))
                $val = $val + 0;
        }
    }
    

    Adding a numeric string to 0 produces a numeric type in PHP and correctly identifies the type so floating point numbers will not be truncated into integers.

提交回复
热议问题