PHP SQL将Select语句转换为变量以进行数据库插入

时间:2018-05-01 08:13:38

标签: php mysql mysqli

我目前正在创建一个Quiz Builder,我对一些数据库插入有轻微的问题。我在代码中尝试做的是在测验表中插入测验标题和描述,然后创建测验ID。我想从复选框中插入此测验ID以及类ID值。任何建议/意见将不胜感激。

注意:我知道我应该使用与我目前使用的相比准备语句。一旦我的主要功能正常工作,我计划解决这个问题。

 <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 个答案:

答案 0 :(得分:0)

以下是您的代码的工作示例如何(使用评论中的一些建议更改)。我保留了原始代码,但更改了脚本中的位置和顺序。

配置HTML和PHP是您应该始终瞄准的事情之一。将所有PHP代码放在一起后,删除重复项或不必要的内容(包括最后插入的id的超级SELECT查询)。

我添加了一些评论以获得额外的解释。其余部分基本上没有被触及=)

<?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>