rana aqib Javeed rana aqib Javeed - 1 month ago 12
PHP Question

I'm designing a signup page in codeigniter but my form validation is not working

Here is my code:

controller/register.php

function register() {
$this->load->view('pages/register');
}

function validation() {
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|is_unique[register1.email]');
$this->form_validation->set_rules('password', 'Password', 'trim|required');

if ($this->form_validation->run() == FALSE) {
$this->load->view('pages/register');
} else {
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'pass' => $this->input->post('password')
);
$result = $this->register_m->registration($data);
}


models/register_m.php

function registration($data) {
foreach($data as $key => $value){
$a = explode(',', $key)[0];
}
$this->db->select('*');
$this->db->from('register1');
$this->db->where('email',email);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {
$this->db->insert('register1', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}


Now the problem is I do not get how to validate my email. Either this email is already register before or not. Can you please also visit my code to tell me if I have made a mistake during coding.

Answer Source

Using is_unique[register1.email] will look for the occurance in your register1 table for you. If it exists it will flag an error. See Form Validation errors in the user guide.

So in your model, you have a big mistake...

NOTE: This is untested

 $this->db->where('email',email); // what is email? a constant??
function registration($data) {
    // Does the email address already exist    
    $this->db->select('*');
    $this->db->from('register1');
    $this->db->where('email', $data['email']); // email is already in your data array
    $this->db->limit(1);
    $query = $this->db->get();
    if ($query->num_rows() == 0) {
        // No so we can save it
        $this->db->insert('register1', $data);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        }
    } else {
        // The email address already exists so leave
        return FALSE;
    }
}

And you don't really need to check the email address again in your model but it's not harmful to do so depending on what else may be calling this... I don't know.

Update: Something to consider... When you are passing in arrays you should really test that the indexes like 'email' actually exist. You should test that all your expected $data entries exist before using it in database updates and inserts etc... Although at Design time, if you make a mistake with your $data entries, it will show up so you can fix it...