提供带有数组的准备好的语句 [英] Supply a prepared statement with an array

查看:88
本文介绍了提供带有数组的准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can I use a prepared statement in Postgres to add multiple values? When I saw that things are added to the prepared statement with array($val), it sort of occurred to me that I should be able to supply an array of values to be put in my table. Is this wildly incorrect? When I tried, I saw in my db table only Array. I don't know if it is an actual array, but I'm guessing, just the word, as the column is a simple 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"));

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

Otherwise, why is the one value supplied as an array?

推荐答案

不是,您插入了文本Array ...如果$ column的类型是文本,则您的代码应读取

No it's not, You inserted the text Array... if the type of $column is text your code should read

$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中作为数组是合法的,则代码应读取

or if you defined $column as text[] which is legal in postgresql as array the code should read

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

这篇关于提供带有数组的准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆