1

我可以在 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"));

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

4

2 回答 2

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));
于 2012-09-17T20:52:41.507 回答
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 数组获取时,将其反序列化。

于 2012-09-17T20:48:31.460 回答