【发布时间】:2018-02-01 21:50:57
【问题描述】:
我正在制作一个投票页面,用户可以在其中对多个投票进行投票,这些投票根据类别有不同的答案。为了简单起见:
代码说明
我有 2 个 foreach 循环:第一个循环遍历所有民意调查,并将它们打印出来。第二个遍历投票的所有可用答案。从 category_id 收到多个答案。每次投票下都会打印出答案。当前显示的方式是每个投票及其相应的答案都打印在彼此下方,有点像列表。
我想要什么
我想要一个下拉菜单,它会在单击时显示所有可用的民意调查。单击投票时,它必须显示投票本身和相应的答案。
我对此很陌生,我希望这不是太要求,如果是这样,我希望你至少可以为我指明正确的方向。
代码
<!-- Voting form -->
<h3> Pollpagina </h3>
<?php
//prepare statement to select all polls
$get_polls = $db->prepare('SELECT * FROM polls');
$get_polls->execute();
$all_polls = $get_polls->fetchAll();
//treat every poll as an individual poll
foreach($all_polls as $single_poll) {
?>
<!-- Create a form for each poll, with the corresponding answers as radio buttons -->
<form method="post" action="">
<div class="poll">
<?php
//get textual poll and its corresponding id and category
$poll_id = $single_poll['id'];
$poll = $single_poll['poll'];
$category = $single_poll['category_id'];
//echo each poll
echo $poll, "<br>";
//prepare statement for getting all the answers from a specific category
$category_answers = $db->prepare('SELECT answer FROM answers WHERE category_id = ?');
$category_answers->bindValue(1, $category, PDO::PARAM_STR);
$category_answers->execute();
$all_answers = $category_answers->fetchAll();
//create a radio button for each answer
foreach($all_answers as $single_array_answer) {
$single_answer = array_shift($single_array_answer);
?>
<input type="radio" name="radio" value="<?php print_r($single_answer); ?>"> <?php print_r($single_answer); ?> <br>
<?php
}
?>
<!-- If a vote has been submitted, the value tag will send the corresponding poll id -->
<button type="submit" name="submit" value="<?php print_r($poll_id); ?>"</button>Submit
</div>
</form>
<?php
}
?>
【问题讨论】:
-
使用 PHP 访问服务器上的数据。用于更改客户端上的代码的 JavaScript。学习 AJAX。
标签: javascript php html foreach