0
\$\begingroup\$

I would like to know if there is a better/shorter/cleaner/resource saving method for this snippet of php code with codeigniter? Thanks.

$code = $this->uri->segment(3);

if (!$code) {
    // validation
    $this->form_validation->set_rules('code', 'PassCode', 'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this->form_validation->run() == true) {
        $code = $this->input->post('code');
        $user_id = $this->user_model->getUserId($code);
        if (empty($user_id)) {
            $data['errorMessage'] = 'Your code is not valid.';
        } else {
            redirect('user/profile');   
        }
    }
} else {
    $user_id = $this->user_model->getUserId($code);
    if (empty($user_id)) {
        $data['errorMessage'] = 'Your code is not valid.';
    } else {
        redirect('user/profile');   
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Check out the codeigniter style guide: codeigniter.com/user_guide/general/styleguide.html For example, instead of if (!$code), write if ( ! $code). In my opinion, codeigniter's style guide is my favorite for php. \$\endgroup\$ – Matthew Mar 21 '12 at 18:30
  • \$\begingroup\$ Your code makes no sence, if( ! $code ) validate else grab user ? Your naming convention is also a little muddled, code = id . \$\endgroup\$ – Philip Mar 21 '12 at 19:20
2
\$\begingroup\$
if ($this->form_validation->run() == true)

is redundant, just use...

if ($this->form_validation->run())

Also, you can move the whole if (empty($user_id)) block outside to the end to avoid duplicating it:

$code = $this->uri->segment(3);

if (!$code) {
    // validation
    $this->form_validation->set_rules('code', 'PassCode',
        'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this->form_validation->run()) {
        $code = $this->input->post('code');
        $user_id = $this->user_model->getUserId($code);
    }
} else {
    $user_id = $this->user_model->getUserId($code);
}

if (empty($user_id)) {
    $data['errorMessage'] = 'Your code is not valid.';
} else {
    redirect('user/profile');   
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.