My situation is I am inserting a new row into table users
where user_id is the primary key and auto incremented. I need the value of that auto inc'ed user_id key to use in another insert for a separate table to set default settings for the newly added user.
Is there a way to get the values of an insert after it has happened... in this case whatever default value user_id ends up being since it is auto inc'ed? Or... will I be forced to do a select right after this insert to find its value?
//insert the user
$stmt = $db->prepare("
INSERT INTO users (
computer_id,
username,
timestamp
)
VALUES (
:computer_id,
:username,
:timestamp
)
");
//bindings
$binding = array(
'computer_id' => $result['computer_id'],
'username' => $_POST['username'],
'timestamp' => time()
);
$added_user = $stmt->execute($binding);
//successfully added the user
if($added_user)
{
//add defaults for this user
$stmt = $db->prepare("
INSERT INTO defaults (
user_id,
default1,
default2
)
VALUES (
:user_id,
:default1,
:default2
)
");
//bindings
$binding = array(
'user_id' => **need this value from above insert**
'default1' => $default1,
'default2' => $default2
);
$status = $stmt->execute($binding);
}