I'm trying to change my PHP statement to Yii2. Here's the original code:
$sql = "select id from users where member_type='d'";
$max = @mysql_num_rows($r=mysql_query($sql));
for($i=0;$i<$max;$i++){
$demo2=mysql_fetch_assoc($r);
some_functions($demo2['id'], 'something');
}
I'm new to Yii2 framework and trying to convert it to Yii2 but have no idea how. I'm doing this function under a modal file.
Here's what I can do at best:
$max= Yii::$app->dbFxprimus->createCommand("select count(id) from ". $this->tableName() ." where member_type='d'")->queryAll();
for($i2=0;$i2<$max;$i2++){
$demo=mysql_fetch_assoc($max); //this is definitely wrong, help me to fix this, I don't know what is the Yii2 function for this.
some_function($demo['id'], 'something');
}
Can anyone help me to fix this?
First of all you need to build query and get the results.
1) If you don't have model, you can do it like that:
use yii\db\Query;
...
$users = (new Query())
->select('id')
->from('users')
->where(['member_type' => 'd'])
->all()
Alternatively you can build query with Yii::$app->db->createCommand()
, but this is better looking.
2) If you have model, and want get results as associative arrays:
use app\models\User;
...
$users = User::find()
->select('id')
->where(['member_type' => 'd'])
->asArray()
->all();
Then just loop through and apply your function:
foreach ($users as $user) {
some_function($user['id'], 'something');
}
And you need replace some_function
to call of some method class, because it's OOP.
P.S. Take your time and read the docs. It's covered there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With