fetchObject example


  public function testSessionWrite() {
    $user = $this->drupalCreateUser([]);
    $this->drupalLogin($user);
    $connection = Database::getConnection();

    $query = $connection->select('users_field_data', 'u');
    $query->innerJoin('sessions', 's', '[u].[uid] = [s].[uid]');
    $query->fields('u', ['access'])
      ->fields('s', ['timestamp'])
      ->condition('u.uid', $user->id());
    $times1 = $query->execute()->fetchObject();

    // Before every request we sleep one second to make sure that if the session     // is saved, its timestamp will change.
    // Modify the session.     sleep(1);
    $this->drupalGet('session-test/set/foo');
    $times2 = $query->execute()->fetchObject();
    $this->assertEquals($times1->access, $times2->access, 'Users table was not updated.');
    $this->assertNotEquals($times1->timestamp, $times2->timestamp, 'Sessions table was updated.');

    
$dumper->addRoutes($collection);

    $this->fixtures->createTables($connection);

    $dumper->dump(['provider' => 'test']);

    $record = $connection->select('test_routes', 'tr')
      ->fields('tr')
      ->condition('name', 'test_route')
      ->execute()
      ->fetchObject();

    $loaded_route = unserialize($record->route);

    $this->assertEquals('test_route', $record->name, 'Dumped route has correct name.');
    $this->assertEquals('/test/{my}/path', $record->path, 'Dumped route has correct pattern.');
    $this->assertEquals('/test/%/path', $record->pattern_outline, 'Dumped route has correct pattern outline.');
    // Verify that the dumped route has the correct fit. Note that 5 decimal     // equals 101 binary.     $this->assertEquals(5, $record->fit, 'Dumped route has correct fit.');
    $this->assertInstanceOf(Route::class$loaded_route);
  }

  
$join_cond = ($this->connection->condition('AND'))
      ->condition('t1.name', $t1_name)
      ->condition('t2.name', $t2_name);
    $query = $this->connection->select('test', 't1');
    $query->innerJoin('test', 't2', $join_cond);
    $query->addField('t1', 'name', 't1_name');
    $query->addField('t2', 'name', 't2_name');

    $num_records = $query->countQuery()->execute()->fetchField();
    $this->assertEquals(1, $num_records, 'Query expected to return 1 row. Actual: ' . $num_records);
    if ($num_records == 1) {
      $record = $query->execute()->fetchObject();
      $this->assertEquals($t1_name$record->t1_name, 'Query expected to retrieve name ' . $t1_name . ' from table t1. Actual: ' . $record->t1_name);
      $this->assertEquals($t2_name$record->t2_name, 'Query expected to retrieve name ' . $t2_name . ' from table t2. Actual: ' . $record->t2_name);
    }
  }

}
$nid = $node->id();
    $count = $this->database->query("SELECT COUNT([cid]) FROM {comment_field_data} [c] INNER JOIN {forum_index} [i] ON [c].[entity_id] = [i].[nid] WHERE [c].[entity_id] = :nid AND [c].[field_name] = 'comment_forum' AND [c].[entity_type] = 'node' AND [c].[status] = :status AND [c].[default_langcode] = 1", [
      ':nid' => $nid,
      ':status' => CommentInterface::PUBLISHED,
    ])->fetchField();

    if ($count > 0) {
      // Comments exist.       $last_reply = $this->database->queryRange("SELECT [cid], [name], [created], [uid] FROM {comment_field_data} WHERE [entity_id] = :nid AND [field_name] = 'comment_forum' AND [entity_type] = 'node' AND [status] = :status AND [default_langcode] = 1 ORDER BY [cid] DESC", 0, 1, [
        ':nid' => $nid,
        ':status' => CommentInterface::PUBLISHED,
      ])->fetchObject();
      $this->database->update('forum_index')
        ->fields([
          'comment_count' => $count,
          'last_comment_timestamp' => $last_reply->created,
        ])
        ->condition('nid', $nid)
        ->execute();
    }
    else {
      // Comments do not exist.       // @todo This should be actually filtering on the desired node language
'column7'  => [
          'type' => 'varchar',
          'length' => 20,
          'default' => 'default value',
        ],
      ],
    ];
    $this->schema->createTable($table_name$table_specification);

    // Insert a row and check that columns have the expected default values.     $this->connection->insert($table_name)->fields(['column1' => 1])->execute();
    $result = $this->connection->select($table_name, 't')->fields('t', ['column2', 'column3', 'column4', 'column5', 'column6', 'column7'])->condition('column1', 1)->execute()->fetchObject();
    $this->assertNull($result->column2);
    $this->assertSame('200', $result->column3);
    $this->assertSame('1.23', $result->column4);
    $this->assertSame("'s o'clock'", $result->column5);
    $this->assertSame("o'clock", $result->column6);
    $this->assertSame('default value', $result->column7);

    // Force SQLite schema to create a new table and copy data by adding a not     // field with an initial value.     $this->schema->addField('test_table', 'new_column', ['type' => 'varchar', 'length' => 20, 'not null' => TRUE, 'description' => 'Added new column', 'initial' => 'test']);

    

  public function eventDetails($event_id) {
    $dblog = $this->database->query('SELECT [w].*, [u].[uid] FROM {watchdog} [w] LEFT JOIN {users} [u] ON [u].[uid] = [w].[uid] WHERE [w].[wid] = :id', [':id' => $event_id])->fetchObject();

    if (empty($dblog)) {
      throw new NotFoundHttpException();
    }

    $build = [];
    $severity = RfcLogLevel::getLevels();
    $message = $this->formatMessage($dblog);
    $username = [
      '#theme' => 'username',
      '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser(),
    ];

  public function fetchAssoc() {
    return $this->fetch(\PDO::FETCH_ASSOC);
  }

  /** * {@inheritdoc} */
  public function fetchObject(string $class_name = NULL, array $constructor_arguments = NULL) {
    if ($class_name) {
      $row = $this->clientStatement->fetchObject($class_name$constructor_arguments);
    }
    else {
      $row = $this->clientStatement->fetchObject();
    }

    if ($row === FALSE) {
      $this->markResultsetFetchingComplete();
      return FALSE;
    }

    $this->setResultsetCurrentRow($row);
    
$this->assertEquals(27 * 2, $record->{$age_double_field}, 'Fetched double age expression is correct.');
    $this->assertEquals(27 * 3, $record->{$age_triple_field}, 'Fetched triple age expression is correct.');
  }

  /** * Tests adding multiple fields to a SELECT statement at the same time. */
  public function testSimpleSelectMultipleFields() {
    $record = $this->connection->select('test')
      ->fields('test', ['id', 'name', 'age', 'job'])
      ->condition('age', 27)
      ->execute()->fetchObject();

    // Check that all fields we asked for are present.     $this->assertNotNull($record->id, 'ID field is present.');
    $this->assertNotNull($record->name, 'Name field is present.');
    $this->assertNotNull($record->age, 'Age field is present.');
    $this->assertNotNull($record->job, 'Job field is present.');

    // Ensure that we got the right record.     // Check that all fields we asked for are present.     $this->assertEquals(2, $record->id, 'ID field has the correct value.');
    $this->assertEquals('George', $record->name, 'Name field has the correct value.');
    
class Batch extends DatabaseQueue {

  /** * Overrides \Drupal\Core\Queue\DatabaseQueue::claimItem(). * * Unlike \Drupal\Core\Queue\DatabaseQueue::claimItem(), this method provides * a default lease time of 0 (no expiration) instead of 30. This allows the * item to be claimed repeatedly until it is deleted. */
  public function claimItem($lease_time = 0) {
    try {
      $item = $this->connection->queryRange('SELECT [data], [item_id] FROM {queue} q WHERE [name] = :name ORDER BY [item_id] ASC', 0, 1, [':name' => $this->name])->fetchObject();
      if ($item) {
        $item->data = unserialize($item->data);
        return $item;
      }
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
    return FALSE;
  }

  
$rows = $query->execute()->fetchCol();

    $this->assertSame('Function value 1', $rows[0]);
  }

  /** * Tests SELECT query with all fields from a table with a reserved name. */
  public function testSelectReservedWordTableAllFields() {
    $query = $this->connection->select('virtual');
    $query->fields('virtual');
    $result = $query->execute()->fetchObject();

    $this->assertSame('Function value 1', $result->function);
  }

  /** * Tests SELECT count query from a table with a reserved alias. */
  public function testSelectReservedWordAliasCount() {
    $query = $this->connection->select('test', 'character');
    $num_records = $query->countQuery()->execute()->fetchField();

    

            }

            return $this->customResultObject[$className];
        }

        if ($this->rowData !== null) {
            $this->dataSeek();
        }
        $this->customResultObject[$className] = [];

        while ($row = $this->fetchObject($className)) {
            if (is_subclass_of($row, Entity::class) && method_exists($row, 'syncOriginal')) {
                $row->syncOriginal();
            }

            $this->customResultObject[$className][] = $row;
        }

        return $this->customResultObject[$className];
    }

    /** * Returns the results as an array of arrays. * * If no results, an empty array is returned. */
/** * Tests SQL injection via database query array arguments. */
  public function testArrayArgumentsSQLInjection() {
    // Attempt SQL injection and verify that it does not work.     $condition = [
      "1 ;INSERT INTO {test} (name) VALUES ('test12345678'); -- " => '',
      '1' => '',
    ];
    try {
      $this->connection->query("SELECT * FROM {test} WHERE [name] = :name", [':name' => $condition])->fetchObject();
      $this->fail('SQL injection attempt via array arguments should result in a database exception.');
    }
    catch (\InvalidArgumentException $e) {
      // Expected exception; just continue testing.     }

    // Test that the insert query that was used in the SQL injection attempt did     // not result in a row being inserted in the database.     $result = $this->connection->select('test')
      ->condition('name', 'test12345678')
      ->countQuery()
      
foreach ($fields as $field_name) {
      $field_storage = FieldStorageConfig::loadByName($entity_type$field_name);
      $table = $table_mapping->getDedicatedDataTableName($field_storage);

      $record = \Drupal::database()
        ->select($table, 'f')
        ->fields('f')
        ->condition('f.entity_id', $id)
        ->condition('f.revision_id', $id)
        ->execute()
        ->fetchObject();

      if ($record->langcode != $langcode) {
        $status = FALSE;
        break;
      }
    }

    $this->assertTrue($status$message);
  }

}
/** * Fetches the next row and returns it as an object. * * @param string $class OPTIONAL Name of the class to create. * @param array $config OPTIONAL Constructor arguments for the class. * @return mixed One object instance of the specified class. * @throws Zend_Db_Statement_Exception */
    public function fetchObject($class = 'stdClass', array $config = array())
    {
        try {
            return $this->_stmt->fetchObject($class$config);
        } catch (PDOException $e) {
            throw new Zend_Db_Statement_Exception($e->getMessage()$e->getCode()$e);
        }
    }

    /** * Retrieve a statement attribute. * * @param integer $key Attribute name. * @return mixed Attribute value. * @throws Zend_Db_Statement_Exception */

    }

    // Calculate normalization, which is the max of all the search scores for     // positive keywords in the query. And note that the query could have other     // fields added to it by the user of this extension.     $normalize_query->addExpression('SUM([i].[score] * [t].[count])', 'calculated_score');
    $result = $normalize_query
      ->range(0, 1)
      ->orderBy('calculated_score', 'DESC')
      ->execute()
      ->fetchObject();
    if (isset($result->calculated_score)) {
      $this->normalize = (float) $result->calculated_score;
    }

    if ($this->normalize) {
      return TRUE;
    }

    // If the normalization value was zero, that indicates there were no     // matches to the supplied positive keywords.     $this->status |= SearchQuery::NO_KEYWORD_MATCHES;
    
Home | Imprint | This part of the site doesn't use cookies.