Er.KT
Er.KT

Reputation: 2860

Yii2 mysql_real_escape_string

Below is the my code :

<?php
$sql2 = "Select * from table ";
for($i=0;$i<count($val);$i++){
$sql2.=" where(column1 LIKE '%".$val[$i]."%' OR "
    . "column2 LIKE '%".$val[$i]."%' OR "
    . "column3 LIKE '%".$val[$i]."%' OR "
    . "column4 LIKE '%".$val[$i]."%' OR "
    . "column5 LIKE '%".$val[$i]."%' OR "
    . "column6 LIKE '%".$val[$i]."%' OR "
    . "column7 LIKE '%".$val[$i]."%') ";
}

Now how to add mysql_real_escape_string here ?

option is like to do ->where('status=:status', [':status' => $status]) but here how can i pass such params ?

Upvotes: 0

Views: 1447

Answers (2)

cetver
cetver

Reputation: 11839

First of all, mysql_ extension is deprecated and Yii do not use it. You need to escape query parameters.

Solution, based on your question:

$query = new \yii\db\Query();
$query
    ->from('table')
    ->andFilterWhere([
        'OR',
        ['LIKE', 'column1', $val[0]],
        ['LIKE', 'column2', $val[1]],
        ['LIKE', 'column3', $val[2]],
        ['LIKE', 'column4', $val[3]],
        ['LIKE', 'column5', $val[4]],
        ['LIKE', 'column6', $val[5]],
        ['LIKE', 'column7', $val[6]]
    ]);

I thinks you need this:

$val = range(1,10);
$query = new \yii\db\Query();
$query->from('table');
foreach ($val as $v) {
    $query
        ->orFilterWhere([
            'OR',
            ['LIKE', 'column1', $v],
            ['LIKE', 'column2', $v],
            ['LIKE', 'column3', $v],
            ['LIKE', 'column4', $v],
            ['LIKE', 'column5', $v],
            ['LIKE', 'column6', $v],
            ['LIKE', 'column7', $v],
        ]);
}

Additional info:

$cc = $query->createCommand();
// debug query
var_dump($cc->rawSql); // returns SQL query with the substituted parameters
var_dump($cc->sql); // returns SQL query with placeholders 
var_dump($cc->params); // returns the placeholders 
// run query
var_dump($cc->queryAll());

Upvotes: 1

lalithkumar
lalithkumar

Reputation: 3540

You can do like below with Query in yii2.And you have to add Query in header.

use yii\db\Query;

$query = new Query;
$query->select('*')
      ->from('table')
      ->where(['=','status',$status]);
for($i=0;$i<count($val);$i++){
      $query->orWhere(['like',column1,$val[$i]]);
}
    $command = $query->createCommand();

Upvotes: 1

Related Questions