基于MySQL列数据类型的动态PHP FORM创建

时间:2014-05-26 19:54:44

标签: php mysql sql

如何通过" select"来了解从数据库中提取的每列的类型?所以我可以在表单中动态添加正确的输入类型吗?

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点;既不完美,但两者都有效。

首先,如果你知道表名和列名,你可以这样做:

SELECT data_type, character_maximum_length, numeric_precision 
  FROM information_schema.COLUMNS
 WHERE TABLE_SCHEMA = DATABASE()
   AND TABLE_NAME='table'
   AND COLUMN_NAME='column'

根据当前数据库中的tablecolumn名称,这将为您提供构建字段所需的一些基本信息。 data_type的值包括以下内容:

bigint     64-bit integer
char       fixed length character string
datetime   date and time
decimal    decimal
double     64-bit IEEE-754 floating point
enum       enumerated type (small integer)
float      32-bit IEEE-754 floating point
geometry   Geo extension type
int        32-bit integer
longblob   binary large object, up to 4 gigabytes in size
longtext   text large object, up to 4 gigabytes in size
mediumblob binary large object, up  16 megabytes in size
mediumint  integer in range [0-16 megabytes]
mediumtext text large object, up to 16 megabytes
smallint   integer [0-65535]
text       text large object, up to 64k bytes
time       time of day
timestamp  UNIX style timestamp
tinyint    integer [0-255]
tinyblob   binary "large" object up to 255 bytes
tinytext   text "large" object up to 255 bytes
varchar    variable length character string

其次,当您使用SELECT语句从RDMS(MySQL或其他)获取结果集时,您总是会收到一些描述列的信息 - 一些元数据。您可以使用mysqli :: fetch_fields或其他apis中的等效调用来检索它。在这种情况下,您将获得编码值,如下所述:http://www.php.net/manual/en/mysqli-result.fetch-fields.php