我正在尝试在我的数据库问题文本中插入/更新两个值并输入。在添加一行时插入了questiontext,并在需要时成功更新。但是,我在插入类型或更新它时都没有成功。有什么帮助吗?
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;
答案 0 :(得分:1)
实际上我觉得你对网页的基本生命周期感到有点困惑。
第一次加载页面时可能是因为点击了菜单或链接,因此没有数据需要处理。如果按下某个表单<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':
中实际无法获取的数据,因为当你生成的按钮实际被按下而字段中有数据时,它实际上不会运行这个案例它将运行另一个,因为在这种情况下您创建的按钮将导致另一个案例完全运行。