function Connection::query

Same name in this branch
  1. 8.9.x core/lib/Drupal/Core/Database/Driver/mysql/Connection.php \Drupal\Core\Database\Driver\mysql\Connection::query()
  2. 8.9.x core/lib/Drupal/Core/Database/Driver/pgsql/Connection.php \Drupal\Core\Database\Driver\pgsql\Connection::query()
Same name in other branches
  1. 9 core/modules/pgsql/src/Driver/Database/pgsql/Connection.php \Drupal\pgsql\Driver\Database\pgsql\Connection::query()
  2. 9 core/lib/Drupal/Core/Database/Connection.php \Drupal\Core\Database\Connection::query()
  3. 10 core/modules/pgsql/src/Driver/Database/pgsql/Connection.php \Drupal\pgsql\Driver\Database\pgsql\Connection::query()
  4. 10 core/lib/Drupal/Core/Database/Connection.php \Drupal\Core\Database\Connection::query()
  5. 11.x core/modules/pgsql/src/Driver/Database/pgsql/Connection.php \Drupal\pgsql\Driver\Database\pgsql\Connection::query()
  6. 11.x core/lib/Drupal/Core/Database/Connection.php \Drupal\Core\Database\Connection::query()

Executes a query string against the database.

This method provides a central handler for the actual execution of every query. All queries executed by Drupal are executed as PDO prepared statements.

Parameters

string|\Drupal\Core\Database\StatementInterface $query: The query to execute. In most cases this will be a string containing an SQL query with placeholders. An already-prepared instance of StatementInterface may also be passed in order to allow calling code to manually bind variables to a query. If a StatementInterface is passed, the $args array will be ignored. It is extremely rare that module code will need to pass a statement object to this method. It is used primarily for database drivers for databases that require special LOB field handling.

array $args: An array of arguments for the prepared statement. If the prepared statement uses ? placeholders, this array must be an indexed array. If it contains named placeholders, it must be an associative array.

array $options: An associative array of options to control how the query is run. The given options will be merged with self::defaultOptions(). See the documentation for self::defaultOptions() for details. Typically, $options['return'] will be set by a default or by a query builder, and should not be set by a user.

Return value

\Drupal\Core\Database\StatementInterface|int|string|null This method will return one of the following:

  • If either $options['return'] === self::RETURN_STATEMENT, or $options['return'] is not set (due to self::defaultOptions()), returns the executed statement.
  • If $options['return'] === self::RETURN_AFFECTED, returns the number of rows affected by the query (not the number matched).
  • If $options['return'] === self::RETURN_INSERT_ID, returns the generated insert ID of the last query as a string.
  • If either $options['return'] === self::RETURN_NULL, or an exception occurs and $options['throw_exception'] evaluates to FALSE, returns NULL.

Throws

\Drupal\Core\Database\DatabaseExceptionWrapper

\Drupal\Core\Database\IntegrityConstraintViolationException

\InvalidArgumentException

See also

\Drupal\Core\Database\Connection::defaultOptions()

10 calls to Connection::query()
Connection::handleQueryException in core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
Wraps and re-throws any PDO exception thrown by static::query().
Connection::nextId in core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
Retrieves an unique ID from a given sequence.
Connection::popCommittableTransactions in core/lib/Drupal/Core/Database/Connection.php
Commit all the transaction layers that can commit.
Connection::pushTransaction in core/lib/Drupal/Core/Database/Connection.php
Increases the depth of transaction nesting.
Connection::query in core/lib/Drupal/Core/Database/Driver/mysql/Connection.php
Executes a query string against the database.

... See full list

2 methods override Connection::query()
Connection::query in core/lib/Drupal/Core/Database/Driver/mysql/Connection.php
Executes a query string against the database.
Connection::query in core/lib/Drupal/Core/Database/Driver/pgsql/Connection.php
Executes a query string against the database.

File

core/lib/Drupal/Core/Database/Connection.php, line 608

Class

Connection
Base Database API class.

Namespace

Drupal\Core\Database

Code

public function query($query, array $args = [], $options = []) {
    // Use default values if not already set.
    $options += $this->defaultOptions();
    if (isset($options['target'])) {
        @trigger_error('Passing a \'target\' key to \\Drupal\\Core\\Database\\Connection::query $options argument is deprecated in drupal:8.0.x and will be removed before drupal:9.0.0. Instead, use \\Drupal\\Core\\Database\\Database::getConnection($target)->query(). See https://www.drupal.org/node/2993033', E_USER_DEPRECATED);
    }
    try {
        // We allow either a pre-bound statement object or a literal string.
        // In either case, we want to end up with an executed statement object,
        // which we pass to PDOStatement::execute.
        if ($query instanceof StatementInterface) {
            $stmt = $query;
            $stmt->execute(NULL, $options);
        }
        else {
            $this->expandArguments($query, $args);
            // To protect against SQL injection, Drupal only supports executing one
            // statement at a time.  Thus, the presence of a SQL delimiter (the
            // semicolon) is not allowed unless the option is set.  Allowing
            // semicolons should only be needed for special cases like defining a
            // function or stored procedure in SQL. Trim any trailing delimiter to
            // minimize false positives.
            $trim_chars = "  \t\n\r\x00\v";
            if (empty($options['allow_delimiter_in_query'])) {
                $trim_chars .= ';';
            }
            $query = rtrim($query, $trim_chars);
            if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
                throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
            }
            $stmt = $this->prepareQuery($query);
            $stmt->execute($args, $options);
        }
        // Depending on the type of query we may need to return a different value.
        // See DatabaseConnection::defaultOptions() for a description of each
        // value.
        switch ($options['return']) {
            case Database::RETURN_STATEMENT:
                return $stmt;
            case Database::RETURN_AFFECTED:
                $stmt->allowRowCount = TRUE;
                return $stmt->rowCount();
            case Database::RETURN_INSERT_ID:
                $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
                return $this->connection
                    ->lastInsertId($sequence_name);
            case Database::RETURN_NULL:
                return NULL;
            default:
                throw new \PDOException('Invalid return directive: ' . $options['return']);
        }
    } catch (\PDOException $e) {
        // Most database drivers will return NULL here, but some of them
        // (e.g. the SQLite driver) may need to re-run the query, so the return
        // value will be the same as for static::query().
        return $this->handleQueryException($e, $query, $args, $options);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.