2012-09-17 72 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