duanliang4009 2014-11-21 18:18
浏览 42
已采纳

PDO事务最后在table1中插入id以在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?

  • 写回答

1条回答 默认 最新

  • dtqpw68806 2014-11-21 18:26
    关注

    Use the function instead:

    $last_id = $db->lastInsertId();

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料