我需要从我的数据库输出问题,以便用户可以在注册过程中回答这些问题。每个问题都有2个与之相关的选项,现在每个问题都输出到网站两次,每个问题下面有一个选项。我需要每个问题出现一次,其相关选项出现在它下面。请参阅下面的代码。
<?php
$sql = "SELECT Question_ID, Question FROM Questions;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0):
while($row = mysqli_fetch_assoc($result)):
$questionid = (int)$row['Question_ID'];
?>
<label><?php echo $row['Question'];?></label><input type="hidden" value="<?php echo $row['Question_ID'];?>"/>
<?php
$query = "SELECT Choice_ID, Choice FROM Choices WHERE Question_ID = '$questionid';";
$results = mysqli_query($conn, $query);
$resultsCheck = mysqli_num_rows($results);
if($resultsCheck > 0):
while($rows = mysqli_fetch_assoc($results)):
?>
<br><select id="choice">
<option value="<?php echo $rows['Choice_ID']; ?>"><?php echo $rows['Choice']; ?></option>
</select><br/>
<?php
endwhile;
endif;
endwhile;
endif;
?>
答案 0 :(得分:1)
您的问题中没有<form>
,我想您知道自己在做什么,并且知道如何处理自<input>
和<select>
以来发布的数据元素没有任何name
属性。
正如Strawberry建议的那样,建议使用准备好的陈述。
我已经更改了您的代码以满足您的需求。在您的代码中,您必须从<select>
循环中取出while
代码,然后只拥有<option>
代码在循环中。
所以代码将是这样的:
<?php
$sql = "SELECT Question_ID, Question FROM Questions;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0):
while($row = mysqli_fetch_assoc($result)):
$questionid = (int)$row['Question_ID'];
echo '<label>'.$row['Question'].'</label><input type="hidden" value="'.$row['Question_ID'].'">';
$query = "SELECT Choice_ID, Choice FROM Choices WHERE Question_ID = '$questionid';";
$results = mysqli_query($conn, $query);
$resultsCheck = mysqli_num_rows($results);
if($resultsCheck > 0):
$string = '<br><select id="choice">';
while($rows = mysqli_fetch_assoc($results)):
$string .= '<option value="'.$rows['Choice_ID'].'">'.$rows['Choice'].'</option>';
endwhile;
$string .= '</select><br>';
echo $string;
endif;
endwhile;
endif;
?>
答案 1 :(得分:0)
像这样组织你的代码(为便于阅读而简化)
while($question = mysqli_fetch_assoc($result))
{
echo "<label for='q'>...; // print question
echo "<select name='answer'>"
while ($answer = mysqli_fetch_assoc($results))
{
echo '<option>'.$answer.</option>';
}
echo '</select>';
}