Couchbase N1QL 的 select 语句在 PHP 中带有命名参数
Couchbase N1QL's select statement with named parameters in PHP
我试图在 PHP 中使用 N1QL...第一个正在运行:
1)
$query = CouchbaseN1qlQuery::fromString("select count(*) from mybucket where type = 'user'");
$res = $myBucket->query($query);
输出:
array(1) {
[0]=>
object(stdClass)#3 (1) {
[""]=>
int(58)
}
}
2) 当我更改为命名参数时,它失败了:
$query = CouchbaseN1qlQuery::fromString("select count(*) from mybucket where type = $type");
$res = $myBucket->query($query, ['type' => 'user']);
我收到 'PHP Notice: Undefined variable: type...' 错误
任何人都可以帮助指导我在 PHP 中为 N1QL 使用命名参数的正确语法吗?
我的 couchbase 服务器是 4.1
看来您的方向是正确的。问题是您在 PHP 字符串中使用 $type
,这导致 PHP 处理器尝试用名为 type
的变量替换它。您应该将 N1QL 字符串用单引号而不是双引号括起来,以避免 PHP 解释器尝试进行此类字符串处理。
还有 Couchbase PHP SDK 提供 API 用于设置命名参数:
$query = CouchbaseN1qlQuery::fromString('SELECT airportname FROM `travel-sample` WHERE city=$city AND type=$airport');
$query->namedParams(['city' => "Los Angeles", 'type' => "airport"]);
这是提供命名参数的首选方式。
我试图在 PHP 中使用 N1QL...第一个正在运行: 1)
$query = CouchbaseN1qlQuery::fromString("select count(*) from mybucket where type = 'user'");
$res = $myBucket->query($query);
输出:
array(1) {
[0]=>
object(stdClass)#3 (1) {
[""]=>
int(58)
}
}
2) 当我更改为命名参数时,它失败了:
$query = CouchbaseN1qlQuery::fromString("select count(*) from mybucket where type = $type");
$res = $myBucket->query($query, ['type' => 'user']);
我收到 'PHP Notice: Undefined variable: type...' 错误
任何人都可以帮助指导我在 PHP 中为 N1QL 使用命名参数的正确语法吗?
我的 couchbase 服务器是 4.1
看来您的方向是正确的。问题是您在 PHP 字符串中使用 $type
,这导致 PHP 处理器尝试用名为 type
的变量替换它。您应该将 N1QL 字符串用单引号而不是双引号括起来,以避免 PHP 解释器尝试进行此类字符串处理。
还有 Couchbase PHP SDK 提供 API 用于设置命名参数:
$query = CouchbaseN1qlQuery::fromString('SELECT airportname FROM `travel-sample` WHERE city=$city AND type=$airport');
$query->namedParams(['city' => "Los Angeles", 'type' => "airport"]);
这是提供命名参数的首选方式。