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

时间:2018-01-24 07:02:44

标签: php pdo

我有两个mysql表

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

关系:Table1->id是主键,Table2->idfk是外键

如何使用PDO在两个关系表中同时插入行。

1 个答案:

答案 0 :(得分:0)

使用以分号(insert

分隔的2 ;个查询
INSERT INTO `Table1` (`id`, `empid`, `status`) VALUES (0, 11, 0);
INSERT INTO `Table2` (`idfk`, `paycodeidfk`, `amount`) VALUES (0, 22, 99);

用于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;
?>