2012-09-17 71 views
1

我可以在Postgres中使用預準備語句來添加多個值嗎?當我看到事物被添加到array($val)準備好的聲明中時,我想到應該能夠提供一系列值放在我的表中。這是瘋狂的不正確?當我嘗試時,我在我的db表中看到只有Array。我不知道它是否是一個實際的陣列,但我猜測,只是這個詞,因爲這個列是一個簡單的character variable用數組提供準備語句

$tag = array('item1', 'item2', 'item3'); 

// Prepare a query for execution 
$result = pg_prepare($dbconn, "my_query", "INSERT INTO $table ($column) VALUES ($1)"); 

// Execute the prepared query. Note that it is not necessary to escape 
// the string "Joe's Widgets" in any way 
$result = pg_execute($dbconn, "my_query", array("$tag")); 

否則,爲什麼一個值作爲數組提供?

+0

該值作爲數組提供以滿足準備好的stmt中的所有可能變量。你的情況只是令人困惑,因爲你準備好的查詢只需要一個。考慮「INSERT INTO my_table(a,b,c,d)值($ 1,$ 2,$ 3,$ 4);」 –

回答

0

你可以嘗試序列化:

$tag = array('item1', 'item2', 'item3'); 
$tag = serialize($tag); 
// Prepare a query for execution 
$result = pg_prepare($dbconn, "my_query", "INSERT INTO $table ($column) VALUES ($1)"); 

// Execute the prepared query. Note that it is not necessary to escape 
// the string "Joe's Widgets" in any way 
$result = pg_execute($dbconn, "my_query", $tag); 

然後,當你想從數據庫得到它作爲一個PHP數組,反序列化它。

+0

,在我的記錄中給了我一個像這樣的對象:a:3:{i:0; s:5:「item1」; i:1; s:5:「item2」; i:2; s:5 :「item3」;}' – 1252748

+0

沒錯,現在要把它變回一個PHP數組,你必須使用反序列化($ yourarray); – AdamGold

+0

,但它開始作爲一個PHP數組......我不明白.. – 1252748

1

不,這不是,你插入的文本數組...如果$列的類型是文本你的代碼應該閱讀

$tag = array('item1', 'item2', 'item3'); 

// Prepare a query for execution 
$result = pg_prepare($dbconn, "my_query", "INSERT INTO $table ($column) VALUES ($1)"); 

// Execute the prepared query. Note that it is not necessary to escape 
// the string "Joe's Widgets" in any way 
foreach($tag as $i) 
    $result = pg_execute($dbconn, "my_query", array($i)); 
/// alternatively you could try this if you really wanna insert a text as array of text without using text[] type - uncomment line below and comment the 2 above 
// $result = pg_execute($dbconn, "my_query", array(json_encode($tag))); 

,或者如果你定義$列文本[]這是PostgreSQL的法律作爲數組代碼應該讀取

$tag = array('item1', 'item2', 'item3'); 

// Prepare a query for execution 
$result = pg_prepare($dbconn, "my_query", "INSERT INTO $table ($column) VALUES ($1)"); 

// Execute the prepared query. Note that it is not necessary to escape 
// the string "Joe's Widgets" in any way 
$tmp = json_encode($tag); 
$tmp[0] = '{'; 
$tmp[strlen($tmp) - 1] = '}'; 
$result = pg_execute($dbconn, "my_query", array($tmp)); 
+1

我得到這個錯誤:'警告:pg_execute()期望參數3是數組,字符串給出' – 1252748

+0

現在就試試吧,對不起,我沒有測試代碼,試圖儘可能快地幫助。 – xception

+0

我給你的3個版本之一應該適合你的需求,postgresql非常聰明,我建議你在那裏使用文本[]作爲類型並相應插入(最後一個) - 應該適合大多數需求 – xception