我正在尝试在数据库问题文本和类型中插入/更新两个值。在添加一行时插入问题文本,并在需要时成功更新。但是我在插入类型或更新类型上都没有成功。有什么帮助吗?

 case 'Addquiz':

         $sql = "SELECT id,questiontext,type FROM questioninfo ORDER BY type DESC ";

         $result = mysqli_query($con,$sql);
         $selectedtable  = "<form method='post' action=''>\n";
         $selectedtable .= "<table class='sortable'>\n<tr><th>Question</th><th>Type</th></tr>\n";

         while($row = mysqli_fetch_assoc($result)) {

             $rowID = $row['id'];
             $text = $row['questiontext'];
             $type = $row['type'];

            $selectedtable .= "<tr>
<td><input type='text' name='QuestionText[$rowID]' value='$text'></td><td><select name='type[$rowID]'><option selected='selected'></option><option value='$type'>Performace</option><option value='$type'>Loyalty</option></select></td></tr>\n";

         }
         $selectedtable .= "</table>\n";
         $selectedtable .= "<input type='submit' name='submit' value='Update' style='width:80px; height:30px; text-align:center; padding:0px;'>\n";
         $selectedtable .= "<input type='submit' name='addquestion' value='Add Question' style='width:140px; height:30px; text-align:center; padding:0px;'>\n";
         $selectedtable .= "</form>\n";

         if(isset($_POST['submit'])) {
             foreach($_POST['QuestionText'] as $rowID => $text) {

                 $sql = "UPDATE questioninfo
                         SET questiontext = '$text',
                             type = '$type'
                         WHERE id = '$rowID'";
                  mysqli_query($con,$sql);
             }

          }
          if(isset($_POST['addquestion'])) {
              $sql="INSERT INTO `questioninfo` (`ID`) VALUES (NULL)";
               mysqli_query($con,$sql);
        }


    break;

最佳答案

实际上,我认为您对带有表单的网页的基本生命周期有些困惑。

第一次加载页面时,可能是由于单击菜单或链接而导致的,因此将没有数据要处理。如果按下表单的<input type='submit' ....>按钮之一,则只能尝试处理用户输入。

因此,用于处理表单的代码的基本布局应类似于以下内容:

<?php

    if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) { // or 'GET'

        // The user has pressed the submit button

        // Check that all required fields are present in $_POST/$_GET

        // check for which button was pressed if more than one button exists
        // Do any database access/updates etc based on validated inputs
        // Store any error message in an array for example to be used
        // in the main HTML generating phase

        // set a flag or 2 so in the HTML generating phase you know
        // what flavor of page you want the user to see
        // based on what the just did.
    } // end of user input processing


    // So now we generate the HTML for the initial page ( no user input )
    // or possibly tailor what we output depending upon
    // what the user entered and we processed above
    // and any flags we set above to control what this
    // screen should look like


如果仔细观察,您的脚本将尝试处理在case 'Addquiz':中实际上不可用的数据,因为当实际按下生成的按钮并且其中包含字段时,它实际上不会运行,在这种情况下它将运行另一个因为您在这种情况下创建的按钮将导致另一种情况完全运行。

10-06 14:23
查看更多