AR Issue

I have a very simple registration table:


CREATE TABLE tbl_register (id, email, activation_code, created);

When the user registers, I am able to insert into this table and generate an activation link that they must click to complete the registration process. The url I generate contains just the activation code.

In my activate controller I have this:




public function actionRegister() {

      if (isset($_GET['activation_code'])) {

            $code = $_GET['activation_code'];

            $register = new Register('activate');

            $register->attributes = array('activation_code'=>$code);

            if ($register->validate()) {

                  $email = $register->email;  <-- returning null

                  ...

            }

      }

}



My question is how to force the AR to grab the email from the database? I don’t understand why it isn’t by default trying to get this value from the database? One way is to do an explicit find after validate, but I would prefer if I didn’t do any explicit sql.

It returns null cause you are not loading any specific Register.

What do you mean? Isn’t the activation code specific?

You should retrieve a record from the db instead of creating a new instance of your model, don’t you think so?




public function actionRegister() {

    if (isset($_GET['activation_code'])) {

        $code = $_GET['activation_code'];

        $register = Register::model()->findByAttributes(array('activation_code'=>$code));

        if ($register != null) {

            $email = $register->email; // will now return the associated email

            ...

        }

    }

}



Yeah this is exactly what I ended up doing

By the way, using $_GET this way is bad practise and can lead to SQL injection attacks, you should do something like this:


public function actionRegister($activation_code=false) {

    if ($activation_code) {

        $register = Register::model()->findByAttributes(array('activation_code'=>$activation_code));

        if ($register != null) {

            $email = $register->email; // will now return the associated email

            ...

        }

    }

}

Typically I would agree with you but in this particular case AR takes care of these kind of things for the developer so you don’t have to :)

Maybe, but it’s still ugly, and not needed since Yii has action parameter binding ;)

I would also say that generally POST should be used for anything which changes data on the server (I’m presuming here that you will be saving the validation state).