2013-10-23 45 views
-1

我有一個有很多領域的PHP表單。我想要的是動態地將字段添加到在PostgreSQL表中插入值的查詢,具體取決於這些字段的內容。如果一個字段(例如date,int等)爲空,我不希望它在查詢中,因爲它在等待要插入的值時試圖插入到表中時會導致「語法錯誤」。請幫助!動態SQL INSERT

編輯

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)' 
+0

聽起來像你的查詢有很好的語法。 到目前爲止你做了什麼?你應該顯示你正在構建的代碼/查詢,以便人們能夠提供幫助。 –

+0

[動態SQL插入查詢]的可能重複(http://stackoverflow.com/questions/10944989/dynamic-sql-insert-query) – tailor

+0

裁縫,我檢查了這個鏈接,但我不認爲它是一樣的。那傢伙向表中添加字段,而不是查詢。 Allan至今爲止的查詢是正確的。只是一個簡單的INSERT。我想要一個保存按鈕,但所有的字段都必須有值。如果沒有,我會解釋一個語法錯誤。 – GsetIT

回答

3

在你的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); 

如有問題PLZ一提。

+0

正如我所解釋的查詢工作正常。這是一個準備好的語句,所以不需要轉義或引用,值來自數組。 $ params = array(...);這不是我的問題所在。 – GsetIT