提供带有数组的预准备语句

时间:2012-09-17 20:46:48

标签: php postgresql prepared-statement

我可以在Postgres中使用预准备语句来添加多个值吗?当我看到用array($val)将事情添加到准备好的语句中时,我发现我应该能够提供一个值列表放在我的表中。这是非常不正确的吗?当我尝试时,我在我的数据库表中只看到了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"));

否则,为什么一个值作为数组提供?

2 个答案:

答案 0 :(得分:1)

不,不是,你插入了文本数组......如果$ column的类型是你的代码应该读的文本

$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)));

或者如果你将$ column定义为text [],这在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 :(得分: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数组时,将其反序列化。