在PHP中以测验游戏的单选按钮格式获取数据

时间:2017-06-07 07:22:42

标签: php mysql database radio-button

我已将数据静态存储在数据库中。它有5 col一个问题和4 col。寻求答案。基本上它是一个测验游戏格式。现在我想以4列的单选按钮的形式从数据库中获取数据。如何实现该方法。目前我正在以正常文本模式获取。

这是代码

 <?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully<br><br>";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo " A) " . $row["Answer1"]. "<br>";
    echo " B) " . $row["Answer2"]. "<br>";
    echo " C) " . $row["Answer3"]. "<br>";
    echo " D) " . $row["Answer4"]. "<br>";
}
} else {
 echo "0 results";
}
$conn->close();

?>

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你只想把答案放到单选按钮上。你可以这样做:

while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo ' A) <input type="radio" value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
    echo ' B) <input type="radio" value="'.$row["Answer2"].'">'.$row["Answer2"].'<br>';
    echo ' C) <input type="radio" value="'.$row["Answer3"].'">'.$row["Answer3"].'<br>';
    echo ' D) <input type="radio" value="'.$row["Answer4"].'">'.$row["Answer4"].'<br>';
}

答案 1 :(得分:0)

如果我理解你的问题。
如果你的数据库字段包含单选按钮的html代码,那么你需要:

使用htmlspecialchars_decode

stripslashes

替换以下行..

 echo " A) " . $row["Answer1"]."<br>";

echo htmlspecialchars_decode(stripslashes($row["Answer1"]));

否则使用简单的PHP代码来显示前端

<input type='radio' name="ans" value="1" > <?php echo $row["Answer1"]; ?>
<input type='radio' name="ans" value="2" > <?php echo $row["Answer2"]; ?>

<input type='radio' name="ans" value="3" > <?php echo $row["Answer3"]; ?>
<input type='radio' name="ans" value="4" > <?php echo $row["Answer4"]; ?>

之后检查值并在帖子上验证ans

答案 2 :(得分:0)

为什么你不尝试选择收音机?但如果我没有弄错的话,这就是你要找的东西

<input type="radio" name="'.$row["Answer1"].'" value="'.$row["Answer1"].'" />
then just validate in your javascript if the radio button has a value make it checked.