admin管理员组

文章数量:1294426

I want to use LIKE in query Drupal 10, use this

    $result = $connection->query("SELECT node_field_data.nid , node_field_data.title
      FROM `node_field_data` 
      WHERE node_field_data.title LIKE :pattern", [
              ':pattern' => '%' . $connection->escapeLike($q) . '%', 
            ])->fetchAll();

Got error

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in ....

I want to use LIKE in query Drupal 10, use this

    $result = $connection->query("SELECT node_field_data.nid , node_field_data.title
      FROM `node_field_data` 
      WHERE node_field_data.title LIKE :pattern", [
              ':pattern' => '%' . $connection->escapeLike($q) . '%', 
            ])->fetchAll();

Got error

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in ....

Share edited Feb 17 at 8:28 Gautam Bothra 6252 gold badges9 silver badges27 bronze badges asked Feb 12 at 12:33 morteza hosseinimorteza hosseini 274 bronze badges 1
  • increase the wait_timeout please refer stackoverflow/questions/33250453/… – Viswanath Polaki Commented Feb 20 at 6:46
Add a comment  | 

1 Answer 1

Reset to default 0

It’s possible that the "MySQL server has gone away" error is happening due to how the query is being executed. Using query() with raw SQL can sometimes cause issues, especially with large datasets or long-running queries.

Switching to Drupal’s Query Builder (select()) might help because:

  • It automatically handles database escaping, reducing security risks.
  • It manages database connections better, which might help with the MySQL issue.
  • It’s easier to read and maintain in a Drupal environment.

Here’s an alternative approach that might work better:

$search_str = 'some title';
$query = \Drupal::database()
  ->select('node_field_data', 'n')
  ->fields('n', ['nid', 'title']);
$query->condition('n.title', '%' . $query->escapeLike($search_str) . '%', 'LIKE');
$results = $query->execute()->fetchAll();

This method keeps the query structured and ensures Drupal is handling connections efficiently.

That said, without knowing more details about the dataset size or server configuration, it’s hard to say for sure if this will completely resolve the issue. It might also be worth checking MySQL settings like max_allowed_packet or wait_timeout if the error persists.

本文标签: 39393939 LIKE mysql query in drupal 10 use escapeLikeStack Overflow