2011-06-10 17 views
-1

我無法找到答案,爲什麼此查詢不正常工作的問題:與查詢

$query = pg_query($connect, sprintf("INSERT INTO table (uid, urzid, time_start, time_stop2, date_start, date_stop, cycle) VALUES ($uid, $pom, '$time1', '$time2', '$data1', '$data2', $cykl)")); 

我得到一個警告:PG_QUERY()[FUNCTION.PG查詢]:查詢失敗:ERROR:語法錯誤在「或」附近「,」在字符96

在我看來,錯誤與'。'$ time1,$ Time2和$ date1,$ date2是符合日期和時間的格式。

回答

2

我們不能猜測哪些內容是在您的變量。 請運行這段代碼,結果貼:

echo "INSERT INTO table (uid, urzid, time_start, time_stop2, date_start, date_stop, cycle) VALUES ($uid, $pom, '$time1', '$time2', '$data1', '$data2', $cykl)"; 

你會發現語法錯誤。

要避免這種錯誤(更重要的是爲了防止SQL injection),最好的方法是使用庫如PDO並使用placeholders作爲變量。

更新:現在我們能看到的變量是什麼樣子,試試這個:

$query = pg_query($connect, "INSERT INTO table (uid, urzid, time_start, time_stop2, date_start, date_stop, cycle) VALUES ('$uid', '$pom', '$time1', '$time2', '$data1', '$data2', '$cykl')"); 

不要忘記看看最佳實踐上述評論,但是。

+0

INSERT INTO REZERWACJE_URZ(UID,URZID,TIME_START ,time_stop,date_start,date_stop,cycle)VALUES(,7,'8:00','9:30','2011-06-09','2011-06-09',1) – Mateusz 2011-06-10 09:06:16

+0

好吧so $ uid是一個空字符串,導致',7,...' – Benjamin 2011-06-10 09:08:16

+0

請看看我的更新答案。 – Benjamin 2011-06-10 09:10:19

0

嘗試扭轉引用, 「=>」,」=>「......總是爲我節省了很多的痛苦。

+0

然而你可以跳過你的變量;) – metaforce 2011-06-10 09:02:23

+0

這樣做會阻止他的變量插入,並進一步中斷查詢。你認爲它會完成什麼? – meagar 2011-06-10 13:44:33

+0

nvm對變量進行插值,將它們設置爲manualy,並使用字符串連接;) – metaforce 2011-06-13 07:15:50

5

你必須提供的格式功能sprintf

doc

而且,有一個在所有的sprintf在這種情況下,沒有需求。

+1

+1,'sprintf()'在您使用它的方式中沒有用處。請正確使用它,並手動轉義您的變量,或再次使用現代工具,如[PDO](http://php.net/manual/en/book.pdo.php) – Benjamin 2011-06-10 09:06:03

0

你必須添加額外的參數:

$world = "World"; 
$foo = sprintf("Hello %s", $world); 

然而,正如你在一個雙引號的字符串你不需要的sprintf:

$foo = "Hello $world";