Using a foreach loop with a Yii 2 query

For some reason this isn’t working. The error I get is “undefined index” for cu_id for the line

$cu_id = $rows[‘cu_id’];

I think I’m just totally using the querybuilder wrong with the foreach loop. Any help with the proper syntax for this? Thanks!





$query = new Query;

		

		$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]);

	

	

	foreach ($query as $rows) {


		$cu_id = $rows['cu_id'];

		

		echo"CU ID: $cu_id<br /><br />";


	}

	



You are iterating through the Query object, not the query result.

See: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html

You probably wanted this:


$rows = (new \yii\db\Query())

    ->select(['cu_id'])

    ->from('cu_emails')

    ->where(['creator_id' => $user_id, 'email' => $email])

    ->all();


    foreach ($rows as $row) {


        $cu_id = $row['cu_id'];


        echo "CU ID: $cu_id<br /><br />";


    }