N1QL Queries Using the PHP SDK with Couchbase Server

To issue N1QL queries, you should create a CouchbaseN1qlQuery object, and pass it to the query method in the CouchbaseBucket class.
A few variants of such a query exist:

Simple queries, which are only strings and do not use placeholders;

Parameterized queries, which use numbered or named placeholders.

You can create each via the corresponding factory method on CouchbaseN1qlQuery passing into it the statement as a string.

The return value from query() is an instance of stdClass.
Iterating over the rows property of the object will yield the rows returned by the server for the given query.
Each row is either a stdClass instance (which is the default) or a nested array depending on the third argument $json_asarray.

Placeholders

You can use N1QL placeholders in the query.
Placeholders allow you to specify variable constraints for an otherwise constant query.
A named or poditional parameter is a placeholder for a value in the WHERE, LIMIT or OFFSET clause of a query.
To use placeholders, manually construct a CouchbaseN1QLQuery object with the base query string, and pass an array of arguments for named or positional placeholders to namedParams or positionalParams methods respectively:

Be careful with placeholders and PHP interpolation, as they both use $ (dollar sign) for the substitution variable.
If you want to use double quotes for your query string, make sure you escape N1QL placeholders properly.

Query Options

You can set other options in the query object as well:

consistency controls the version of the documents to be scanned, and can either be CouchbaseN1qlQuery::NOT_BOUNDED (which is the default) or CouchbaseN1qlQuery::REQUEST_PLUS (which ensures that only the most recent version of documents are used).

adhoc determines whether the query will be optimized as a prepared statement at the SDK level.
If this is set to false then a prepared reference to this query will be stored on the SDK and used for subsequent queries.