L
L
lexstile2019-07-04 13:28:22
PHP
lexstile, 2019-07-04 13:28:22

How to correctly compose a query with the LIKE operator in sql?

The bottom line is that you need to use the :word variable .
Template: :word% (starts with :word, and then any number of any characters)
Tried like this, does not work:

return $this->db->row('SELECT * FROM words WHERE word LIKE `:word%`', $params);

# запрос
  public function getSearchList($word) {
    $params = [
      'word' => $word,
    ];
    return $this->db->row('SELECT * FROM words WHERE word = :word', $params);
  }
# framework db
  public function query($sql, $params = []) {
    $stmt = $this->db->prepare($sql);
    if (!empty($params)) {
      foreach ($params as $key => $val) {
        if (is_int($val)) {
          $type = PDO::PARAM_INT;
        } else {
          $type = PDO::PARAM_STR;
        }
        $stmt->bindValue(':'.$key, $val, $type);
      }
    }
    $stmt->execute();
    return $stmt;
  }

  public function row($sql, $params = []) {
    $result = $this->query($sql, $params);
    return $result->fetchAll(PDO::FETCH_ASSOC);
  }

  public function column($sql, $params = []) {
    $result = $this->query($sql, $params);
    return $result->fetchColumn();
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kafkiansky, 2019-07-04
@lexstile

$stmt = $this->prepare('SELECT * FROM words WHERE word LIKE :word');
$stmt->execute(['word' => $word . '%']);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question