有没有办法在Codeigniter中将一些值(从一个表单)插入到两个不同的表中?

有没有办法在Codeigniter中将一些值(从一个表单)插入到两个不同的表中?

问题描述:

I am trying to insert the names (First name and Last name) details of a user registering into [first name] and [last name] column of a user_details table. Consequently, the email and password to their respective columns of a snm_users table

How can I possibly achieve this in Codeigniter?

Here is snippet of my input form:

<input type="text" name="fname">
<input type="email" name="email">
<input type="password" name="password">

And here is the model to handle database:

class User_model extends CI_Model {
    public function register ($enc_password){
        $data = array(
            'fname' => $this->input->post('fname'),
            'email' => $this->input->post('email'),
            'password' => $enc_password
        );
        //insert user to database
        return $this->db->insert('snm_users', $data);
    }
}

I believe you are new to CodeIgniter. Better do some research to get a basic idea of how the MVC (Model View Controller) really works. I will give you a basic idea: VIEW is where you use the HTML, like displaying the form, and any output stuff, etc. MODEL is where you write the code for db interactions. Like INSERTIONS, UPDATIONS, SELECT queries, etc. And CONTROLLER is where you do you business logic, validations, etc.

In the code snippet you posted above, you are using the data submitted from the form directly inside your MODEL. Which is kind of not the best approach. Accept it (from $this->input->post() inside your CONTROLLER, and then do the validations and pass it to the MODEL.

And back to your question, you want to insert the first_name and last_name in user_details_table and email and password in another table (snm_users_table)

For this, first do the insertion in your main table. I believe its snm_users_table. And I assume that you have a primarykey named user_id or something to identify each record. So, once you insert in this main User table, you can get the last_insert_id(id of this newly inserted row) using this function: $this->db->insert_id()

Now, you can use this user_id returned by the above function to insert the other details on your second table, which is user_details_table.

You can use TRANSACTIONS during these insertions, so that you won't end up inserting a record in one table and no record in the other table, in case of any errors! Because TRANSACTIONS would help you to rollback the changes in case of any problems!

Read more here: https://www.codeigniter.com/user_guide/database/transactions.html

Hope this will give you an idea. :)