\Drupal\Core\Database\Connection::select
public
function
Prepares and returns a SELECT query object.

Prepares and returns a SELECT query object.

Comments

PabloViquez’s picture

Simple query, which returns all the results in a form of an array of stdClass objects.

Query to be executed: SELECT x.field_a, x.field_b FROM table_x x WHERE x.field_c < 10;

use Drupal\Core\Database\Database;

// Retrieves a \Drupal\Core\Database\Connection which is a PDO instance
$connection = Database::getConnection();

// Retrieves a PDOStatement object
// http://php.net/manual/en/pdo.prepare.php
$sth = $connection->select('table_x', 'x')
    ->fields('x', array('field_a', 'field_b'))
    ->condition('x.field_c', '10', '<');

// Execute the statement
$data = $sth->execute();

// Get all the results
$results = $data->fetchAll(\PDO::FETCH_OBJ);

// Iterate results
foreach ($results as $row) {
    echo "Field a: {$row->field_a}, field b: {$row->field_b}";
}

Thanks to manojapare for the edit

manojapare’s picture

use Drupal\Core\Database\Database;

// Retrieves a \Drupal\Core\Database\Connection which is a PDO instance
$connection = Database::getConnection();

// Retrieves a PDOStatement object
// http://php.net/manual/en/pdo.prepare.php
$sth = $connection->select('table_x', 'x')
->fields('x', array('field_a', 'field_b'))
->condition('x.field_c', '10', '<');

// Execute the statement
$executed = $sth->execute();

// Get all the results
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

// Iterate results
foreach ($results as $row) {
echo "Field a: {$row->field_a}, field b: {$row->field_b}";
}

wheelercreek’s picture

use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$options = array();
$result = $connection->query('SELECT * FROM node WHERE nid = :nid', array(':nid' => 3), $options);

foreach($result as $item) {
var_dump($item);
}

This is actually an example of Connection::query but you might be looking for that. I haven't tested them all but these methods listed for the now deprecated db_query I think also work for this - https://www.drupal.org/docs/7/api/database-api/static-queries