7

Currently I am using the following query to select the data from database

$result = db_query("select data from {config} where name like '%IPPOOL_POOL%' ");
while ($row = $result->fetchObject()) {
  $ips=$row->value;
}

But this generated an error like

Undefined property: stdClass::$value

Please help me to implement same in Drupal 8.

2
  • 1
    You are only selecting the data field, and then try to access value. Of course that doesn't exist? I'm not sure what you expect? Also, querying the config table seems like a very bad idea. Do not query arbitrary tables, always use the API's if available. In this case, the config system.
    – Berdir
    Aug 2, 2016 at 18:24
  • I would recommend you rephrase your question to what you actually want to achieve and then you might get a better question.
    – Berdir
    Aug 2, 2016 at 18:25

2 Answers 2

17

According to Drupal db_like doc page

Get a database connection injected into your service from the container and call escapeLike() on it.

For example,

$injected_database->escapeLike($string);

Try something like:

$database = \Drupal::database();
$result = $database->select('table_name', 't')
    ->fields('t', ['field_1', 'field_2'])
    ->condition('field_1', "%" . $database->escapeLike($string) . "%", 'LIKE')
    ->execute()
    ->fetchAll();

Read Database api in Drupal 8 for a better understanding of database query in drupal 8.

7
  • 1
    db_select is deprecated, Dependency Injection would the best, but for the sake of simplicity you should at least use \Drupal::database()->select() instead in the examples.
    – ssibal
    Aug 2, 2016 at 7:55
  • 1
    @ssibal you right, thanks , I'm going to update my answer
    – Yuseferi
    Aug 2, 2016 at 8:42
  • While all true, that doesn't actually answer the question. db_query() is deprecated but still works perfectly fine, if your query makes sense. The one in the question does not, see my comment above. No amount of refactoring to avoid deprecated functions will change anything about that. db_like() is also only necessary if you have user input that you want to have escaped.
    – Berdir
    Aug 2, 2016 at 18:26
  • @YusefMohamadi, link is 404
    – dresh
    Dec 17, 2018 at 11:32
  • Dead link Database queries in Drupal 8
    – sea26.2
    Nov 11, 2020 at 16:45
0

If you are interested in syntax for query() (not for condition()) then here how to use like:

$db = \Drupal::database();
$oldTablesPrefix = $db->escapeLike('old_') . '%';
$oldTables = $db->query('SHOW TABLES LIKE :prefix', [':prefix' => $oldTablesPrefix])
  ->fetchCol();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.