Kevinvhengst
Kevinvhengst

Reputation: 1702

Posting data twice into the database - CodeIgniter

So i started my first CodeIgniter project, and I'm still learning a lot of things. Right now I've made this user sign-up page.

When the user fills in the sign-up form and presses submit it will trigger the following function:

/**
* Signup validation
*/
public function signup_validation(){
    $this->load->library('form_validation');

    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]');
    $this->form_validation->set_rules('password', 'Password', 'required|trim');
    $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');

    $this->form_validation->set_message('is_unique', "That email address is already is use");

    if($this->form_validation->run()){
        $this->load->model('model_users');

        if ($this->model_users->add_user()){
            echo "user has been added";
        } else {
            echo "Something went wrong";
        }

        $this->model_users->add_user();
    } else {
        $this->load->view('view_signup');
    }
}

This function then makes a call to "model_users" and runs the function "add_user":

public function add_user(){
    $data = array(
        'email' => $this->input->post('email'),
        'password' => $this->input->post('password')
    );

    $query = $this->db->insert('users', $data);

    if ($query){
        return true;
    } else {
        return false;
    }
}

So this codes adds the data in the database fine. The validation works great. But for some reason it adds every user twice. I've tried to figure out what causes this problem, but I cannot seem to find out why.

I've also created another small piece of code where you can add page-categories into the database, the code is very similar, but it does not post twice.

Upvotes: 0

Views: 654

Answers (2)

Gavin
Gavin

Reputation: 2143

You call

$this->model_users->add_user()

twice.

Once in the if statement as a condition and again after the else. Remove the second call.

Upvotes: 2

Ramesh
Ramesh

Reputation: 4293

$this->model_users->add_user() is called twice once inside if() and once after if else.

    if ($this->model_users->add_user()){
        echo "user has been added";
    } else {
        echo "Something went wrong";
    }

    $this->model_users->add_user();

I think you want to remove the below one.

Upvotes: 2

Related Questions