不同表的INSERT和SELECT语句相同页面

时间:2014-03-31 19:04:23

标签: php mysql sql pdo

我正在制作一份啤酒杂志。当我想创建一个新的日记帐分录时,我在日记帐表中插入一行,其中包含我正在品尝的啤酒的ID。啤酒存放在单独的表中。将行插入日志表后,我想从beerData表中选择啤酒,以便在完成输入时将其显示给用户。我的插入工作正常,但我没有得到啤酒名称的任何回报。我尝试过几种不同的东西,但都不起作用。

<?php 

if (isset( $_POST['newJournalEntry'] )) {

    //Define POST Variables
    $beerID = $_POST['id'];

    //Create Record in Beer Journal
    //SQL Query
    $query = "INSERT INTO journal (beerID)
                    VALUES (:beerID);
              SELECT beer FROM beerData 
                    WHERE id = :beerID;";

    //Prepare Query, Bind Parameters, Excute Query
    $STH = $DBH->prepare($query);
    $STH->bindParam(':beerID', $beerID);
    $STH->execute();

    $journal_id = $DBH->lastInsertId();


    while($row = $STH->fetch(PDO::FETCH_ASSOC)){
        echo $row['beer'];
        }

    } else {
echo "Test";
}
?>

第二次尝试:

<?php 

if (isset( $_POST['newJournalEntry'] )) {

    //Define POST Variables
    $beerID = $_POST['id'];

    //Create Record in Beer Journal
    //SQL Query
    $query = "INSERT INTO journal (beerID)
                    VALUES (:beerID)";

    //Prepare Query, Bind Parameters, Execute Query
    $STH = $DBH->prepare($query);
    $STH->bindParam(':beerID', $beerID);
    $STH->execute();

    $journal_id = $DBH->lastInsertId();

    //SQL Query
    $query2 = "SELECT beer FROM beerData WHERE id = :beerID";

    //Prepare Query, Bind Parameters, Execute Query
    $STH2 = $DBH->prepare($query2);
    $STH2->bindParam(':beerID', $beerID);
    $STH2->execute();

    while($row = $STH2->fetch(PDO::FETCH_ASSOC)){
        echo $row['beer'];
        }

    } else {
echo "ELSE!!!";
}   
?>

0 个答案:

没有答案