是否有办法告诉postgres数组中的数据类型?

时间:2022-08-15 16:58:54

I am using a Postgres 9.4 database and have PHP as my front end.

我使用的是Postgres 9.4数据库,并将PHP作为前端。

A general query I may run would look like this:

我可以运行的一般查询如下:

PHP :

PHP:

$query = "select * from some_table";
pg_prepare($connection,"some_query",$query);
$result = pg_execute($connection,"some_query",array());

while ($row = pg_fetch_array($result,null,PGSQL_ASSOC)) {
    echo $row['some_field'];
    echo $row['some_field_1'];
    echo $row['some_field_2'];
}

I am running into a front-end that requires to know the datatype of the column that spits out - specifically I need to know when the echo'd database field is a timestamp column.

我正在运行一个前端,它需要知道spits的列的数据类型——具体来说,我需要知道什么时候echo数据库字段是时间戳列。

Obviously I can tell integers and string, however timestamp is a bit of a different thing.

显然我可以分辨整数和字符串,但是时间戳有点不同。

I suppose I could see if strtotime() returns false, however that seems a little dirty to me.

我想我可以看到strtotime()是否返回false,但是这在我看来有点脏。

So my question is:

我的问题是:

Is there a PHP built-in function that can return a multi-dimensional array of the database row with not only $key=>$value pair but also the datatype?

是否有一个PHP内置函数可以返回一个多维的数据库行数组,该数组不仅包含$key=>$value对,还包含数据类型?

Any help on this would be appreciated - thank you!

如有任何帮助,我们将不胜感激——谢谢!

1 个解决方案

#1


1  

You can query from information_schema.columns and fetch just like any other query:

可以从information_schema查询。列和获取与任何其他查询一样:

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name='some_table'

Or after your query use pg_field_type():

或在查询后使用pg_field_type():

$type = pg_field_type($result, 0);

But you need to know the position of the column in the result so you should (best practice anyway) list the columns. For the above case using 0 would give the type of col1 in the query below::

但是您需要知道列在结果中的位置,所以您应该(无论如何,最佳实践)列出列。对于上述情况,使用0将给出以下查询中的col1类型:

SELECT col1, col2, col3 FROM some_table

#1


1  

You can query from information_schema.columns and fetch just like any other query:

可以从information_schema查询。列和获取与任何其他查询一样:

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name='some_table'

Or after your query use pg_field_type():

或在查询后使用pg_field_type():

$type = pg_field_type($result, 0);

But you need to know the position of the column in the result so you should (best practice anyway) list the columns. For the above case using 0 would give the type of col1 in the query below::

但是您需要知道列在结果中的位置,所以您应该(无论如何,最佳实践)列出列。对于上述情况,使用0将给出以下查询中的col1类型:

SELECT col1, col2, col3 FROM some_table