简体   繁体   English

使用PHP(PDO)在关系表中插入行

[英]Insert Rows in Relational Tables Using PHP (PDO)

I have two mysql tables 我有两个mysql表

Table1 : Columns (id(int pk), empid(int), status( varchar(1) ) )
Table2 : Columns (idfk(int fk), paycodeidfk(int fk), amount(int) )

Relation : Table1->id is Primary Key and Table2->idfk is Foreign Key 关系: Table1->id是主键, Table2->idfk是外键

How could i insert rows at same time in both relational tables using PDO. 我如何使用PDO在两个关系表中同时插入行。

Using 2 insert query separated with semicolon ( ; ) 使用2用分号( ; )分隔的insert查询

INSERT INTO `Table1` (`id`, `empid`, `status`) VALUES (0, 11, 0);
INSERT INTO `Table2` (`idfk`, `paycodeidfk`, `amount`) VALUES (0, 22, 99);

for php code 为PHP代码

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // First Query
        $sql = "INSERT INTO `Table1` (`id`, `empid`, `status`) VALUES (0, 11, 0);";
        $conn->exec($sql);

        // Get lastInsrtId
        $last_id = $conn->lastInsertId();

        // Second Query
        $sql = "INSERT INTO `Table2` (`idfk`, `paycodeidfk`, `amount`) VALUES ({$last_id}, 22, 99);";
        $conn->exec($sql);
    } catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    $conn = null;
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM