Database Basic Examples | Drupal 8

Database Basic Examples

Submitted by Anonymous (not verified) on Fri, 06/10/2016 - 23:50
Question

Drupal 8 Database basic commands / Examples

Select:
    $con = \Drupal\Core\Database\Database::getConnection();
    $query = $con->select('table_name', 't')
        ->fields('t', ['field_1', 'field_2']);
    $result = $query->execute()->fetchAll();

NULL Condition

$query->isNull('t.field_1');
$query->isNotNull('t.field_2');

 

Example : Inset into database

Methode 1. Single row

$con->insert('the_table_name')
->fields([
  'field_1' => 'Value 1',
  'field_2' => 'Value 2',
])
->execute();

Method 2. (Multiple rows)

$con->insert('the_table_name')
->fields(['field_1' ,'field_2'])
->values(['field_1' => 'Val 1','field_2'=>'value 2'])
->values(['field_1' => 'Val 3','field_2'=>'value 4'])
->execute();
#Or also:
$con->insert('the_table_name')
->fields(['field_1' ,'field_2'])
->values(['Val 1','value 2'])
->values(['Val 3','value 4'])
->execute();

Example : DB Merge : Insert or update if fields is already exist

$query = $con->merge('the_table_name')
  ->key(array('the_key_field' => 'THE_KEY_VALUE'))
  ->insertFields(array(
    'timestamp' => date(),
    'count' => 1,
      'field_1' => 'Value 1',
      'field_2' => 'Value 2',
  ))
  ->updateFields(array(
    'timestamp' => date(), // update time
  ))
  ->expression('count', 'count + :inc', array(':inc' => 1)); // update counter
$query->execute();

Read all rows of a table:

$data = $con->select('table_name','t')->fields('t')->execute()->fetchAll(PDO::FETCH_ASSOC);

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.