php postgresql 在查询中插入空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29162662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:16:46  来源:igfitidea点击:

postgresql insert null value on query

phppostgresql

提问by huddreth

In my php code query, i got some error when i will place a null value into the table. The column names "number1","number2", and "number3" are integers and can have a null value.

在我的 php 代码查询中,当我将空值放入表中时出现一些错误。列名“number1”、“number2”和“number3”是整数,可以为空值。

if there is no null value, the query works

如果没有空值,则查询有效

query is like this insert into table(number1,number2,number3) values (1,2,3);

查询就像这样 insert into table(number1,number2,number3) values (1,2,3);

but when I leave a blank value on the input form on the PHP,

但是当我在 PHP 的输入表单上留下一个空白值时,

for example I will not place value for column "number2", the query will look like this.

例如,我不会为“number2”列放置值,查询将如下所示。

insert into table(number1,number2,number3) values (1,,3);

插入 table(number1,number2,number3) 值 (1,,3);

it says ERROR: syntax error at or near "," SQL state: 42601

它说错误:语法错误位于或附近“,”SQL 状态:42601

Does anybody have an idea how to solve this?

有人知道如何解决这个问题吗?

this query is likely to be the solution but is there any other way? insert into table(number1,number2,number3) values (1,null,3);

此查询可能是解决方案,但还有其他方法吗? 插入 table(number1,number2,number3) 值 (1,null,3);

because i got so many variables like that and am a bit lazy to place some conditions like when that variable returns a blank value then value="null"

因为我有很多这样的变量,而且我有点懒惰地放置一些条件,例如该变量返回一个空值然后 value="null"

回答by Simo Kivist?

You insert NULLvalue by typing NULL:

您可以NULL通过键入 NULL 来插入值:

INSERT INTO table(number1,number2,number3) VALUES (1,NULL,3);

If you have a variable and when that variable is empty you want to insert a NULLvalue you can use NULLIFwith the variable enclosed in single quotes to prepare for that (this is somewhat dirty solution as you have to treat the variable as an empty string and then convert it to integer):

如果您有一个变量,并且当该变量为空时,您想要插入一个NULL值,您可以将其NULLIF与用单引号括起来的变量一起使用来为此做准备(这有点肮脏的解决方案,因为您必须将该变量视为一个空字符串,然后将其转换为整数):

INSERT INTO table(number1,number2,number3) VALUES (1,NULLIF('$var','')::integer,3);