How to put sql query in an array in yii

2019-07-10 07:44发布

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'?

标签: mysql yii
2条回答
对你真心纯属浪费
2楼-- · 2019-07-10 08:21

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
}
查看更多
疯言疯语
3楼-- · 2019-07-10 08:21

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 :)

查看更多
登录 后发表回答