0

2 つの異なる db テーブルにデータを公開するフォームがあります。私の取引は以下で見ることができます。

$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 値と同じである必要があります。

そのため、テーブル 1 から最後のインサート ID を取得し、その値をテーブル 2 で使用する必要があります。うまくいかなかった失敗した試みをアウトコメントし、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 に答える