1

I have to run multiple INSERT statements one after the other, but I need to retrieve the primary key of the last inserted row in between, to use in the next INSERT statement. I understand I can do this with SELECT LAST_INSERT_ID();, but I'm not too sure how to use it in my code to store inside the php variable.

function addItem($name, $category, $rating, $user){
    $pdo = Database::connect();
    $sql = "INSERT INTO items (id, category, api, name, api_id) VALUES ('', '". $category ."', '', '". $name ."', '')";
    $pdo->query($sql);
    // $item_id = ???
    $sql = "INSERT INTO ratings (id, user, item, rating) VALUES ('', '". $user ."', '". $item_id ."', '". $rating ."')";
    $pdo->query($sql);
    Database::disconnect();
}
Pim
  • 445
  • 1
  • 8
  • 24

2 Answers2

1

You can use PDO's lastInsertId method like this

$item_id = $pdo->lastInsertId();

http://php.net/manual/en/pdo.lastinsertid.php

Giedrius
  • 1,370
  • 3
  • 14
  • 37
1

Try this:

function addItem($name, $category, $rating, $user){
    $pdo = Database::connect();
    $sql = "INSERT INTO items (id, category, api, name, api_id) VALUES ('', '". $category ."', '', '". $name ."', '')";
    $pdo->query($sql);

    // $item_id = ???
    $item_id = $pdo->lastInsertId();

    $sql = "INSERT INTO ratings (id, user, item, rating) VALUES ('', '". $user ."', '". $item_id ."', '". $rating ."')";
    $pdo->query($sql);
    Database::disconnect();
}
Prince Adeyemi
  • 724
  • 6
  • 12