How to determine column type with PDO?

I need a way to determine the type of database column (varchar / numeric / date / ...) when reading from a database with PDO.

When retrieving values ​​from a database, PDO produces only string values, regardless of the actual type of table column.

Is there any specific way, other than a driver, to get this information? I know there are SQL statements that extract types for any given table, but I would prefer a more general solution.

EDIT: PDOStatement :: getColumnMeta () is useless to me because it is not supported by the PDO driver that I am currently using (Oracle).

+3
source share
6
+2

WraPDO:

$tomet = $sth->getColumnMeta($column_index);
$tomet['type'] = $this->_translateNativeType($tomet['native_type']);

private function _translateNativeType($orig) {
    $trans = array(
        'VAR_STRING' => 'string',
        'STRING' => 'string',
        'BLOB' => 'blob',
        'LONGLONG' => 'int',
        'LONG' => 'int',
        'SHORT' => 'int',
        'DATETIME' => 'datetime',
        'DATE' => 'date',
        'DOUBLE' => 'real',
        'TIMESTAMP' => 'timestamp'
    );
    return $trans[$orig];
}

$sth: PDOStatement- > getColumnMeta

+2

, . - :

SHOW COLUMNS FROM <table> WHERE Field = ?

, :

+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+

. pre-PHP 5.1.0. PDOStatement- > getColumnMeta.

+2

Oracle:

select COLUMN_NAME,
       DATA_TYPE,
       DATA_LENGTH,
       DATA_PRECISION,
       DATA_SCALE
from user_tab_cols
where table_name = '<Table Name>'
order by column_id

SQL

DESCRIBE <Table Name>
0

Postgres:

select
    CHARACTER_MAXIMUM_LENGTH,
    COLUMN_NAME,
    IS_NULLABLE,
    COLUMN_DEFAULT,
    NUMERIC_PRECISION,
    NUMERIC_SCALE,
    UDT_NAME 
from
    INFORMATION_SCHEMA.COLUMNS 
where
    TABLE_NAME = 'table_name'
0
source

Source: https://habr.com/ru/post/1752629/


All Articles