简体   繁体   English

如何通过PHP知道哪些列在postgres中没有null约束?

[英]How to know which columns have not null constraint in postgres via php?

Im trying to build some html input elements via php in order to fill up rows in a postgres table. 我试图通过php构建一些html输入元素,以填充postgres表中的行。

I want to add the attribute "required" to some of the html input elements (those that correspond to the columns that have the NOT NULL constraint). 我想将属性“ required”添加到某些html输入元素(与具有NOT NULL约束的列相对应的元素)。

How can I know which columns have that constraint? 我如何知道哪些列具有该约束?

Using PDO (and suggestion here ), you should be able to pull it off as follows: 使用PDO(并在此处提供建议),您应该能够按以下步骤进行操作:

$q = $dbh->prepare("\d tablename");
$q->execute();
$table_fields = $q->fetchAll();
foreach ($table_fields as $field) {
    if (strpos($field['Modifiers'], 'not null') !== FALSE) {
         // this column ($field['Column']) has a "not null" constraint.
    }
}

Edit : same if you're dead set on using PostgreSQL PHP extension: 编辑 :如果您对使用PostgreSQL PHP扩展名无动于衷,则相同:

$q = pg_query("\d tablename");
while ($row = pg_fetch_array($result)) {
    if (strpos($row['Modifiers'], 'not null') !== FALSE) {
         // this column ($row['Column']) has a "not null" constraint.
    }
}

Use Pomm and it will perform those queries for you to inspect your database with the CLI: 使用Pomm ,它将为您执行这些查询,以使用CLI检查数据库:

$ php vendor/bin/pomm.php pomm:inspect:relation test pika_chu
Relation public.pika_chu
+----+---------------+--------+-----------------------------------------------+---------+---------+
| pk | name          | type   | default                                       | notnull | comment |
+----+---------------+--------+-----------------------------------------------+---------+---------+
| *  | pika_chu_id   | int4   | nextval('pika_chu_pika_chu_id_seq'::regclass) | yes     |         |
|    | some_data     | int4   |                                               | yes     |         |
|    | nullable_data | bpchar |                                               | no      |         |
+----+---------------+--------+-----------------------------------------------+---------+---------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM