Drupal 8 : How to use SELECT query with Syntax and Example

Using the object of core Drupal class we can perform database queries. Select is the data retrieval query that has been done with help of select() of Drupal 8 core class. Below sample show how to use select query in Drupal 8.

Syntax: 

$query = \Drupal::database()->select('TABLE_NAME', 'TABLE_ALIAS');
$query->fields('TABLE_ALIAS', ['FIELD_1', 'FIELD_2', 'FIELD_3', ...]);
$result = $query->execute();
while ($row = $result->fetchAssoc()) {
	print_r ($row['FIELD_1']); // Print FIELD_1 value.
	print_r ($row['FIELD_2']); // Print FIELD_2 value.
	print_r ($row['FIELD_3']); // Print FIELD_3 value.
        ...........
}

Example: 

$query = \Drupal::database()->select('employee', 'emp');
$query->fields('emp', ['employee_id', 'employee_name', 'employee_age']);
$result = $query->execute();
while ($row = $result->fetchAssoc()) {
	$output .= $row['employee_id'];
	$output .= $row['employee_name'];
	$output .= $row['employee_age'];
}

 

Output:

EMPLOYEE_ID EMPLOYEE_NAME EMPLOYEE_AGE
CE 001 Mohan 20
CE 002 Dinesh 17
CE 003 Kumar 25
Category: 

Comments

Jestin (not verified)
Is there a way to add a variable to the search fields? because it isn't working when i add a variable. $domain_query->fields('cdl', [$site_env, 'localized_name']);