我有两个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在两个关系表中同时插入行。
答案 0 :(得分:0)
使用以分号(insert
)
;
个查询
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;
?>