Search code examples
phppdotransactionslast-insert-id

PDO transaction last inserted id in table1 to be used in table2


I have a form where I publish data to two different db tables. You can see my Transaction below.

$db->beginTransaction();
    $sql = "INSERT INTO clients (name, contact_person, phone, email, url)
            VALUES (:name, :contact_person, :phone, :email, :url)";

    $stm = $db->prepare ( $sql );

    $stm->bindParam ( ":name", $name );
    $stm->bindParam ( ":contact_person", $contact_person );
    $stm->bindParam ( ":phone", $phone );
    $stm->bindParam ( ":email", $email );
    $stm->bindParam ( ":url", $url );   

    $client = $stm->execute ();
    //$last_id = $db->lastInsertId;


    $sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
            VALUES (:title, :description, :user_id, :status_id ,:client_id)";

    $stm = $db->prepare ( $sql );

    $stm->bindParam ( ":title", $title );
    $stm->bindParam ( ":description", $description );
    $stm->bindParam ( ":user_id", $user_id );
    $stm->bindParam ( ":status_id", $status_id );
    //$stm->bindParam ( ":client_id", $last_id );

    $task = $stm->execute ();

$db->commit();

However, in my table "task" I have another column "client_id" where I want to bind a value. And the value here, should be the same as the id value that has been auto-incrementet on my clients table.

I therefor need to somehow get the last insertet id from table one, and use that value in table two. I have outcommented my failed attempt, which didn't work, and returned NULL

Can anyone give me some pointers on how to manage this?


Solution

  • Use the function instead:

    $last_id = $db->lastInsertId();