duanjun7801 2018-05-01 08:13
浏览 111
已采纳

PHP SQL将Select语句转换为DB Insert的变量

I am currently in the process of creating a Quiz Builder, I am having a slight issue with some DB inserts. What I am trying to do within the code is insert a Quiz Title and Description to the Quiz table which will in turn create a Quiz ID. I want to insert this Quiz ID along with Class ID values from the checkbox. Any suggestions/advice would be greatly appreciated.

Note: I know I should be using prepare statements compared to what I am currently using. I am planning on fixing this issue once I get my main functionalities working.

 <form method="post" action="#">
                <p>
                    <label>Quiz Title: </label>
                    <input type="text" placeholder="Insert Quiz Title here" name="quizTitle" class="form-control" />
                </p>
                <p>
                    <label>Quiz Description: </label>
                    <input type="text" placeholder="Insert Quiz Description here" name="description" class="form-control"  />
                </p>

<?php

$showAllClasses = "SELECT * FROM class";
mysqli_query($mysqli, $showAllClasses) or die ('Error finding Classes');

$showClassesResult = mysqli_query($mysqli, $showAllClasses);

echo"<table border='1' cellpadding='10' align='center'>";

echo "<tr><th></th><th>Class ID</th><th>Class Name</th><th>Class 
Description</th></tr>";

 //while ($row = mysqli_fetch_assoc($result)){
  while ($row = $showClassesResult->fetch_object()){
  echo "<tr>";
  echo "<td><input type='checkbox' id='" .$row->classID . "' name='check_box[]' value='" .$row->classID . "'></td>";
  echo "<td>" .$row->classID . "</td>";
  echo "<td>" .$row->className . "</td>";
  echo "<td>" .$row->classDesc . "</td>";
  //echo "<td><button type='button' name='add' id='add' data-toggle='modal' data-target='#questionType' class='btn btn-success'>Edit Students</button></td>";
  echo "</tr>";

}

if (isset($_POST['submit'])) {
//Get POST variables
$quizTitle = '"' . $mysqli->real_escape_string($_POST['quizTitle']) . '"';
$description = '"' . $mysqli->real_escape_string($_POST['description']) . '"';
//echo $quizTitle;
//echo $description;

$getQuizIDQuery = "SELECT quizID FROM quiz ORDER BY quizID DESC LIMIT 1";

mysqli_query($mysqli, $getQuizIDQuery) or die ('Error getting Quiz ID');

$result = mysqli_query($mysqli, $getQuizIDQuery);
//$insertedQuizId = $mysqli->insert_id;

//Question query
$quizCreationQuery = "INSERT INTO quiz (quizTitle, description) VALUES($quizTitle, $description)";

foreach ($_POST['check_box'] as $classID) {

$ClassQuizQuery = "INSERT INTO quiz_class(classID, quizID) VALUES ('$classID', '$result')";

//$insert_ClassQuiz = $mysqli->query($ClassQuizQuery) or die($mysqli->error . __LINE__);


//Run Query
$insert_row = $mysqli->query($quizCreationQuery) or die($mysqli->error . __LINE__);

}
}
?>
    </table>
        <div align="center">
                    <input type="submit" name="submit" value="Submit" 
                    class="btn btn-info"/>
         </div>
            </form>
  • 写回答

1条回答 默认 最新

  • douguo7431 2018-05-01 11:10
    关注

    Here's how a working example of your code could look like (with some of the suggested changes from the comments). I kept you original code mostly as is, but changed the placement and order within your script.

    Serparating HTML and PHP is one of the things you should always aim for. Once you have all the PHP code closer together, remove duplicates or unnecessary stuff (including the superflous SELECT query for the last inserted id).

    I added some comments for extra explanation. The rest ist mostly untouched =)

    <?php
    
    
    // first - all code that should always be executed,
    // this will later be used in the html output.
    $showAllClasses = "SELECT * FROM class";
    $showClassesResult = $mysqli->query($showAllClasses) or die ('Error finding Classes');
    
    // now the code that should only be executed on POST request
    if (isset($_POST['submit'])) {
    
        // we only want things to happen if all queries are successful,
        // otherwise we end up with quizzes without class connections.
        $mysqli->begin_transaction();
    
        //Get POST variables
        $quizTitle = '"' . $mysqli->real_escape_string($_POST['quizTitle']) . '"';
        $description = '"' . $mysqli->real_escape_string($_POST['description']) . '"';
    
        //Question query
        $quizCreationQuery = "INSERT INTO quiz (quizTitle, description) VALUES($quizTitle, $description)";
        $mysqli->query($quizCreationQuery) or die($mysqli->error . __LINE__);
    
        // The $mysqli instance knows the last inserted id, so we can just use that.
        $insertedQuizId = $mysqli->insert_id;
    
        foreach ($_POST['check_box'] as $classID) {
            $ClassQuizQuery = "INSERT INTO quiz_class(classID, quizID) VALUES ('$classID', $insertedQuizId)";
            $mysqli->query($ClassQuizQuery) or die($mysqli->error . __LINE__);
        }
    
        // Everything should have worked so we can now commit the transaction
        $mysqli->commit();
    }
    
    // now that we are done with everything, we start with the html output.
    // since we have done all the complicated stuff above, all we have to care
    // about, is the html output and iterating over our classes to create the html table.
    ?>
    
    <form method="post" action="#">
        <p>
            <label>Quiz Title: </label>
            <input type="text" placeholder="Insert Quiz Title here" name="quizTitle" class="form-control"/>
        </p>
        <p>
            <label>Quiz Description: </label>
            <input type="text" placeholder="Insert Quiz Description here" name="description" class="form-control"/>
        </p>
    
        <table border='1' cellpadding='10' align='center'>
            <tr><th></th><th>Class ID</th><th>Class Name</th><th>Class Description</th></tr>
            <?php while ($row = $showClassesResult->fetch_object()): ?>
                <tr>
                <td><input type='checkbox' id='<?= $row->classID ?>' name='check_box[]' value='<?= $row->classID ?>'></td>
                <td><?= $row->classID ?></td>
                <td><?= $row->className ?></td>
                <td><?= $row->classDesc ?></td>
                <td><button type='button' name='add' id='add' data-toggle='modal' data-target='#questionType' class='btn btn-success'>Edit Students</button></td>
                </tr>
            <?php endwhile ?>
        </table>
        <div align="center">
            <input type="submit" name="submit" value="Submit" class="btn btn-info"/>
        </div>
    </form>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝