-1

I'm trying to save the auto incremented ID that'll be created in the table 'accounts' when a new user filled out the registration form in the second table 'userdaten'.

image of table 'accounts'

image of table 'userdata'

The code saves the data in both tables like it should, but I still need to get the auto incremented 'id' from table 'accounts' into my table 'userdaten'

if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {

    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);
    $stmt->execute();
    echo 'Data saved in table accounts';

    $stmt2 = $con->prepare('INSERT INTO userdaten (name, vorname, gebdatum, strasse, hnr, plz, ort) VALUES (?, ?, ?, ?, ?, ?, ?)');
    $stmt2->bind_param('sssssss', $_POST['name'], $_POST['vorname'], $_POST['gebdatum'], $_POST['strasse'], $_POST['hausnummer'], $_POST['plz'], $_POST['ort']);
    $stmt2->execute();
    echo 'Data saved in table userdaten';

I tried to make it work with mysqli_insert_id for the past hour, but I couldn't make it work.

Any idea what I have to change? the code above gives no error and is functional, with the exception that the auto incremented 'id' is only saved in 'accounts'.

Nick
  • 138,499
  • 22
  • 57
  • 95
fl3xf1t
  • 1
  • 2
  • So you want the record in `userdata` to have the same `id` as the one that auto-generated with you insert in `accounts`? – GMB Feb 04 '20 at 22:13
  • yes! the ID in `accounts` gets automatically created after a new user filled out the registration form. now I want the same ID from `accounts` to be saved in the `userdata` table – fl3xf1t Feb 04 '20 at 22:16

1 Answers1

0

You can use LAST_INSERT_ID() to get the auto-increment id value from the last insert query and use it in your current one. So change your userdaten query to:

$stmt2 = $con->prepare('INSERT INTO userdaten (id, name, vorname, gebdatum, strasse, hnr, plz, ort)
                        VALUES (LAST_INSERT_ID(), ?, ?, ?, ?, ?, ?, ?)');
Nick
  • 138,499
  • 22
  • 57
  • 95
  • hey, thank you very much! I thought I tried that earlier, but apparently I f*cked up somewhere, lol. it works now :) appreciate the help, cheers my friend – fl3xf1t Feb 04 '20 at 22:21