【问题标题】:Dynamic SQL INSERT动态 SQL 插入
【发布时间】:2013-11-01 14:18:57
【问题描述】:

我有一个包含许多字段的 PHP 表单。我想要的是动态地将字段添加到在 PostgreSQL 表中插入值的查询中,具体取决于这些字段的内容。如果一个字段(例如日期、int 等)为空,我不希望它出现在查询中,因为当我尝试插入表时它会导致“语法错误”,因为它正在等待插入值。请帮忙!

编辑

INSERT INTO hcd_customermeters ("meterSN", "contractCode",
                "deviceManufacturer", "deviceType",
                "firstInstallationDate", "diameter",
                "pipeID", "operatorCreator", "warehouseDeliveryDate",
                "recordCreation", "SRID") 
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)' 

【问题讨论】:

  • 听起来您的查询有 - 语法不正确。到目前为止你做了什么?您应该展示您正在构建的代码/查询,以便人们能够提供帮助。
  • dynamic SQL insert query的可能重复
  • 裁缝,我检查了那个链接,但我认为它不一样。那家伙将字段添加到表中,而不是查询。艾伦到目前为止我的查询是正确的。只是一个简单的插入。我想要一个保存按钮,但所有字段都必须有值。如果不是,就会发生语法错误,正如我解释的那样。
  • 请举例说明您的问题。您已经创建了表请提及。
  • 已编辑。该表已准备就绪,其中包含记录。我的问题是当我尝试插入新记录时。上面的查询(在 PHP 中这就是 $ 的原因)运行正确。如果相应字段中没有值,例如 pipeID,则会发生错误。

标签: php postgresql select dynamic


【解决方案1】:

在您的 mysql 查询中定义变量名不正确更改名称:

PHP 变量规则:

1) variable starts with the $ sign, followed by the name of the variable
2) variable name must start with a letter or the underscore character
3) **variable name cannot start with a number**
4) variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case sensitive ($y and $Y are two different variables)



$sql_insert = 'INSERT INTO hcd_customermeters ("meterSN", "contractCode", "deviceManufacturer", "deviceType", "firstInstallationDate", "diameter", "pipeID", "operatorCreator", "warehouseDeliveryDate", "recordCreation", "SRID") 
            VALUES ("'.$variableName."', "'.$variableName."', "'.$variableName."',"'.$variableName."', "'.$variableName."', "'.$variableName."', "'.$variableName."', "'.$variableName."', "'.$variableName."', "'.$variableName."',"'.$variableName."')';


mysql_query($sql_insert);

如果有什么问题请提一下。

【讨论】:

  • 正如我解释的查询工作正常。这是一个准备好的语句,因此不需要转义或引用,并且值来自数组。 $params = 数组(...);那不是我的问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2010-10-17
  • 2023-03-23
相关资源
最近更新 更多