phpyii2yii2-advanced-appyii2-user

Retrieve data from database based on current user login in yii2


How to fetch data from database based on current user login? As example, when user login and click the profile bar, it only display his/her data only. I've tried before but it display all data of user.

At personalinfo.php

    <?php foreach ($personals as $user):?><?=Html::encode("{$user->username}")?><?php endforeach;?>
    <?php foreach ($personals as $user):?><?=Html::encode("{$user->user_id}")?><?php endforeach;?>
    <?php foreach ($personals as $user):?><?=Html::encode("{$user->email}")?><?php endforeach;?>

At controller

    public function actionPersonalinfo()
    {
    $query = User::find()->all();
    return $this->render('personalinfo', [
        'personals' => $query
    ]);


    }

I think because of $query = User::find()->all();. But I dont know how to replace it so that it will retrieve data based on current user login. I'm very new with yii2. Sorry and thank you


Solution

  • Replace your code with :

    At personalinfo.php

      User Id :    <?php echo $personals->user_id; ?>
      Username:    <?php echo $personals->username; ?>
      Email   :    <?php echo $personals->email; ?>
    

    At controller

        public function actionPersonalinfo() {
            $query = User::findOne(Yii::$app->user->id);
            return $this->render('personalinfo', [ 'personals' => $query ]);
        }