kevinkt kevinkt - 2 months ago 26
PHP Question

Using foreach loop with Query Builder in Yii 2

For some reason this isn't working. The error I get is "Undefined index: 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 />";

}


Also I'm on the Yii 2 framework in case anyone missed that.

Answer

You query not run.

$query->all()

and then foreach records or

$query->one()

and get data from one record

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

foreach ($results as $rows) {
        $cu_id = $rows['cu_id'];
        echo"CU ID: $cu_id<br /><br />";
}