<?php
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'usename';
$passdb = 'password';
$charset = 'utf8';
if (isset($_POST['user'], $_POST['maker'] )) {
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$hostdb;dbname=$namedb;charset=$charset", $userdb, $passdb, $options);
try{
$conn->beginTransaction();
$stmt = $conn->prepare( ' INSERT INTO `Table1` (`user`, `maker`)
VALUES (:user, :maker ) ' );
$stmt->execute([
'user' => $_POST['user'],
'maker' => $_POST['maker'],
]);
//get the last insert ID
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE `Table1` SET `num` = CONCAT("NUM", :last_id_0) WHERE `numid` = :last_id_1');
$stmt->execute([
'last_id_0' => $last_id,
'last_id_1' => $last_id
]);
echo "New record created. Last ID: " . $last_id;
//commit the changes
$conn->commit();
}catch(PDOException $e){
//roll back the changes on errors
$conn->rollback();
echo $e->getMessage();
}
// Shows the number of affected rows this is pointless (for insert 1 row it's always 1 or an error)
//echo 'Affected rows : '. $stmt->rowCount();
}
?>
我有以下PDO脚本,其中包含一个名为INSERT
的表的Table1
查询和一个UPDATE查询
如果INSERT
查询成功,则UPDATE
查询将UPDATES
中的lastInsertId()和NUM
列Table1
移到带有{ {1}}。
最终结果是三列,分别填充NUM
,NUM
和User
。
现在仅在完成此操作后,我想再添加一个Maker
查询,该查询采用INSERT
中最后插入的ID的NUM
值和最后插入ID的用户值(将其插入第一个Table1
查询中)并将它们INSERT
插入INSERT
我了解它看起来像这样:
Table2
但是两个查询如何共享值?
更新:
( ' INSERT INTO `Table2` (`num`, `user`) VALUES (:num, :user ) ' );