具有多个mySQL查询的PDO脚本

时间:2019-07-17 19:23:44

标签: php mysql pdo

<?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()和NUMTable1移到带有{ {1}}。

最终结果是三列,分别填充NUMNUMUser

现在仅在完成此操作后,我想再添加一个Maker查询,该查询采用INSERT中最后插入的ID的NUM值和最后插入ID的用户值(将其插入第一个Table1查询中)并将它们INSERT插入INSERT

我了解它看起来像这样:

Table2

但是两个查询如何共享值?

更新:

( ' INSERT INTO `Table2` (`num`, `user`) VALUES (:num, :user  ) ' );

0 个答案:

没有答案