Simple while loop to list all rows

[u][b]Simple while loop to literate through all rows and echo two field

[/b][/u]

I assume this is fairly simple (I am a novice to yii/yii2) and am wanting to do a while loop to iterate through the rows/data and echo two fields from within each row.

So far I have created the model and CRUD as well as creating a index file for the frontend.

Contoller




     */

    public function actionIndex()

    {

        $this->layout = 'directory';


        $searchModel = new ShopDirectorySearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }



How can I do the following for while loop but in the yii2 way, as the data/query really should be in the controller function or search model. I know you can use gridview or list view but obviously I only want to echo the values without any additional html or other fields etc





$query = mysql_query("SELECT * FROM shop_directory")or die(mysql_error());

while($row = mysql_fetch_array($query))

{

  $lat = $row['lat'];

  $lon = $row['lon'];


  echo("addmarker($model->lat, $model->lon);\n");




make sure you have a model generated for your shop_directory table


<?php

$query = mysql_query("SELECT * FROM shop_directory")or die(mysql_error());


// above query will tranlate to this in yii active record

$rows = ShopDirectory::findAll();




while($row = mysql_fetch_array($query))

{

  $lat = $row['lat'];

  $lon = $row['lon'];

  echo("addmarker($model->lat, $model->lon);\n");

}


// findAll returns an array you just iterate over the array as normal


foreach ($rows as $row) {

	echo $row->lat;

	echo $row->lon;

}

In your action :




$rows = ShopDirectory::findAll();

if(!empty($rows))

{

  foreach($rows as $row)

  {

    $lat = $row->lat;

    $lon = $row->lon;


    $this->view->registerJs('addmarker("'.$lat.'", "'.$lon.'"."\n");', yii\web\View::POS_END);

    ...

  }

}



Something like this is a good way ;)

you don’t need to check if the result is empty foreach will check if the array is empty it will return immediately