gpt4 book ai didi

php - 提供带有数组的准备好的语句

转载 作者:行者123 更新时间:2023-11-29 13:35:44 26 4
gpt4 key购买 nike

我可以在 Postgres 中使用准备好的语句来添加多个值吗?当我看到使用 array($val) 将内容添加到准备好的语句时,我突然想到我应该能够提供一个值数组以放入我的表中。这是完全不正确的吗?当我尝试时,我在我的数据库表中只看到了 Array。我不知道它是否是一个实际的数组,但我猜,只是这个词,因为该列是一个简单的字符变量

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

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

最佳答案

不,不是,您插入了文本数组...如果 $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));

关于php - 提供带有数组的准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com