0

我有一个表格,我将数据发布到两个不同的数据库表。你可以在下面看到我的交易。

$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();

但是,在我的表“任务”中,我有另一列“client_id”,我想在其中绑定一个值。这里的值应该与我的客户表上自动递增的 id 值相同。

因此,我需要以某种方式从表一中获取最后一个插入 id,并在表二中使用该值。我已经评价了我失败的尝试,但没有成功,并返回 NULL

谁能给我一些关于如何管理这个的指示?

4

2 回答 2

0

请改用该功能:

$last_id = $db->lastInsertId();

于 2014-11-21T18:26:46.730 回答
-1

将第一个 tbl 的执行语句放入 -----> if()条件

并使用 -----> $last_id = $this->conn->lastInsertId();获取 table1 的最后插入 id

替换您的 $sql 查询值 -----> :client_id替换为$last_id

这是正确的代码(从代码中删除星星)

**if(**$client = $stm->execute ()**){**
   **$last_id = $this->conn->lastInsertId();**


    $sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
            VALUES (:title, :description, :user_id, :status_id ,**$last_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();
}
于 2021-08-27T11:20:06.393 回答