How to check if record exists in database

Shilpa Kirad picture Shilpa Kirad · Nov 27, 2012 · Viewed 20k times · Source

In yii I am creating password reset functionality by using a security question. First the user needs to enter his email id. I created emailform.php in views->User1 as

<?php
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'email-form',
    'enableClientValidation'=>true,
    ));
echo CHtml::textField('email');
echo CHtml::submitButton('Send');
$this->endWidget();

In controller I created method as

public function actionPassword() {
    if (isset($_POST['email'])) {
       $email = $_POST['email'];
       //process email....
       //....
    }
    $this->render('_emailForm');
}

Now I want to check whether this email id exists in User table. If it does, then I want to display a security question to him. How can I implement this?

Answer

Kieran Andrews picture Kieran Andrews · Nov 27, 2012

This will help you get started, you would put a method similar to this in your controller and create a view with a password field on it.

public function actionPassword() {
  if(isset($_POST['email'])) {
    $record=User::model()->find(array(
      'select'=>'email',
      'condition'=>'email=:email',
      'params'=>array(':email'=>$_POST['email']))
    );

    if($record===null) {
      $error = 'Email invalid';
    } else {
      $newpassword = 'newrandomgeneratedpassword';
      $record->password = $this->hash_password_secure($newpassword);
      $record->save(); //you might have some issues with the user model when the password is protected for security
      //Email new password to user
    }
  } else {
    $this->render('forgetPassword'); //show the view with the password field
  }
}