MySQL integer field is returned as string in PHP

前端 未结 15 2454
南旧
南旧 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条回答
  •  生来不讨喜
    2020-11-22 17:02

    My solution is to pass the query result $rs and get a assoc array of the casted data as the return:

    function cast_query_results($rs) {
        $fields = mysqli_fetch_fields($rs);
        $data = array();
        $types = array();
        foreach($fields as $field) {
            switch($field->type) {
                case 3:
                    $types[$field->name] = 'int';
                    break;
                case 4:
                    $types[$field->name] = 'float';
                    break;
                default:
                    $types[$field->name] = 'string';
                    break;
            }
        }
        while($row=mysqli_fetch_assoc($rs)) array_push($data,$row);
        for($i=0;$i $type) {
                settype($data[$i][$name], $type);
            }
        }
        return $data;
    }
    

    Example usage:

    $dbconn = mysqli_connect('localhost','user','passwd','tablename');
    $rs = mysqli_query($dbconn, "SELECT * FROM Matches");
    $matches = cast_query_results($rs);
    // $matches is now a assoc array of rows properly casted to ints/floats/strings
    

提交回复
热议问题