Farhad
Farhad

Reputation: 85

How to put sql query in an array in yii

I have a line like this:

 $line= Yii::app()->db->createCommand()->select('line_no')->from('tblvehicleimage') ->where('serial_no=:serial_no', array(':serial_no'=>$model->serial_no)) ->queryScalar();

how to put all the $line data in an array? Is there any way i can use 'mysql_fetch_array'?

Upvotes: 2

Views: 5249

Answers (2)

Let me see
Let me see

Reputation: 5094

Since you want to select only line_no from the table, you can also use queryColumn()

$line = Yii::app()->db->createCommand()
        ->select('line_no')
        ->from('tblvehicleimage')
        ->where('serial_no IN ('.$serial_nos.')')
        ->queryColumn();

If you want one-dimensional array like

array(1,2,3)

as your result then you can use queryColumn()
But if you want

array(array(1),array(2),array(3))

as your answer then you can use queryAll().

Choice is yours :)

Upvotes: 2

Samuel Liew
Samuel Liew

Reputation: 79022

queryScalar means only one record will be retrieved.

You want to use serial_no IN (1, 2, 3) for example, and queryAll() instead of queryScalar().

$serial_nos = array(1, 2, 3);
$serial_nos = implode($serial_nos);

$line = Yii::app()->db->createCommand()
        ->select('line_no')
        ->from('tblvehicleimage')
        ->where('serial_no IN ('.$serial_nos.')')
        ->queryAll();

Once the query is successful, $line will contain an array, you then simply have to loop through the results:

foreach ($line as $key=>$item) {
    // do something with each $item
}

Upvotes: 2

Related Questions