简体   繁体   中英

How to call the SQL LIKE function in Yii2?

Receiving NULL as value when I called this SQL statement (the record exists in the MySQL DB). How can use the LIKE function in Yii2? Thanks.

$command = $connection->createCommand("SELECT user_id
                         FROM User
                            WHERE name LIKE '%:_username%'");

$command->bindParam(':_username',$this->username);
$this->id_user = $command->queryScalar();
$command->execute();

In Yii2 you can use also a activeQuery Notation this way

  $query = new Query;
  $query->select('userid')
      ->from('user')
      ->where(['like', 'user', $this->username );

  $command = $query->createCommand();

  $this->id_user = $command->queryScalar(); 

I think the issue here is with the binding .

Try, using this instead.

$command->bindParam('_username',$this->username);

Also not so sure what's the acceptable syntax for the variables, so if it's still not working try removing the _ and use username on binding... and :username on the query.

I'm not sure, but try to get the first % before the single quote and the last % after the last single quote.

$command = $connection->createCommand("SELECT user_id FROM User WHERE name LIKE %':_username'%");

Binding needs to be done on the entire data not just part of it.

$command = $connection->createCommand("SELECT user_id
                     FROM User
                        WHERE name LIKE :username");

$user = '%' . $this->username . '%';

$command->bindParam(':username',$user);
$this->id_user = $command->queryScalar();
$command->execute();

Just wrap "%value%" in bindValue

 $command = $connection->createCommand("SELECT user_id
                             FROM User
                                WHERE name LIKE ':_username'");

    $command->bindParam(':_username',"%".$this->username."%");
    $this->id_user = $command->queryScalar();
    $command->execute();

Correct Way to bind value with %% is below

 $command->bindParam(':_username',"%".$this->username."%");

just like as PDO we use

I'm using bindValue. You can use like this.. I have a query in my model, and calls the functions on my Controller.

Inside Model:

$query = "SELECT u.id as idUser
FROM vagas_x_candidato vxc
INNER JOIN usuario u ON(u.id = vxc.id_candidato)
WHERE u.nome LIKE :nameUser";

$connection = \Yii::$app->db;
$model = $connection->createCommand($query);
$model->bindValue(":nameUser", '%' . $filter->nameU . '%');
return $model->queryAll();

Inside Controller:

$vxc = new VagasXCandidatoSearch();
$vxc = $vxc->candidatosPesquisaAvancada(); //calls my method on model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM