Get MySQL Query Results as Their Native Data Type?

后端 未结 5 1311
孤城傲影
孤城傲影 2020-11-30 10:03

I have tried fetching MySQL query results using mysql_fetch_row() and mysql_result() and numeric values are being returned as strings.

Is

5条回答
  •  醉酒成梦
    2020-11-30 10:39

    I wrote a function to circuvent this (for PDO):

    /**
     * Converts columns from strings to types according to 
     * PDOStatement::columnMeta
     * 
     * @param PDOStatement $st
     * @param array $assoc returned by PDOStatement::fetch with PDO::FETCH_ASSOC
     * @return copy of $assoc with matching type fields
     */
    function convertTypes(PDOStatement $statement, $assoc)
    {
        for ($i = 0; $columnMeta = $statement->getColumnMeta($i); $i++)
        {
            $type = $columnMeta['native_type'];
    
            switch($type)
            {
                case 'DECIMAL':
                case 'TINY':
                case 'SHORT':
                case 'LONG':
                case 'LONGLONG':
                case 'INT24':
                    $assoc[$columnMeta['name']] = (int) $assoc[$columnMeta['name']];
                    break;
                case 'DATETIME':
                case 'DATE':
                case 'TIMESTAMP':
                    $assoc[$columnMeta['name']] = strtotime($assoc[$columnMeta['name']]);
                    break;
                // default: keep as string
            }
        }
    
        return $assoc;
    }
    

    Of course the type list are not complete and the conversion is oversimplified, but can be useful for start.

提交回复
热议问题