Taylor
Taylor

Reputation: 3141

Codeigniter - Insert into two tables with the user ID in the second

I'm trying to insert into two tables. On my first table, I insert the basic user info. On the second table, I need the user id to set the default text for my site. E.g. "This is your first text. you can click to edit." etc

My code so far:

//adds the basic user info to the users database
 $sql = "INSERT INTO users (first_name, last_name, username, email, password, IP, total_entry, average_entry, date_of_registration, lastactive, account_state)
    VALUES (" . $this->db->escape($first_name) . ",
             " . $this->db->escape($last_name) . ",
             " . $this->db->escape($username) . ",
             '" . $email . "',
             '" . $password . "',
             '" . $IP . "',
             '" . $total_entry . "',
             '" . $average_entry . "',
             '" . $date_of_registration . "',
             '" . $lastactive . "',
             '" . $account_state . "')";  

        //adds the basic entry to the database   
    $data = array(
        'message' => $message,
        'picture' => $picture,
        'uid' => $uid, //problem here, since the $uid is undefined
        'time' => $date_of_registration,
    );

    $this->db->insert('entries', $data);

So I need to save register the user first, then update the second table with teh user's UID.

Whats the best way to do it in codeidniter?

Thanks

Upvotes: 0

Views: 1213

Answers (1)

CodeWithCoffee
CodeWithCoffee

Reputation: 1904

You should use $this->db->insert_id() for uid value in $data array so ,it would be something like :

//adds the basic user info to the users database

$sql = "INSERT INTO users (first_name, last_name, username, email, password, IP, total_entry, average_entry, date_of_registration, lastactive, account_state) VALUES (" . $this->db->escape($first_name) . ", " . $this->db->escape($last_name) . ", " . $this->db->escape($username) . ", '" . $email . "', '" . $password . "', '" . $IP . "', '" . $total_entry . "', '" . $average_entry . "', '" . $date_of_registration . "', '" . $lastactive . "', '" . $account_state . "')";

// Get above inserted id here in variable 

$last_id = $this->db->insert_id();

//adds the basic entry to the database   
$data = array(
    'message' => $message,
    'picture' => $picture,
    'uid' => $last_id, //write $last_id here instead $uid
    'time' => $date_of_registration,
);

$this->db->insert('entries', $data);

And it should work

Upvotes: 1

Related Questions