我找不到我需要的东西。我试图在quizzer创建从数据库中提问。目前,它需要数据库中的所有问题以及我需要它随机提出10个问题。我刚刚开始学习如何编码。
以下是我的问题代码和答案:
<?php
//Set question number
$number = (int) $_GET['n'];
/*
* Get total questions
*/
$query = "SELECT * FROM `klausimai`";
//Get result
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total = $results->num_rows;
/*
* Get Question
*/
$query = "SELECT * FROM `klausimai`
WHERE question_number = $number";
//Get result
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$question = $result->fetch_assoc();
/*
* Get Choices
*/
$query = "SELECT * FROM `atsakymai`
WHERE question_number = $number";
//Get results
$choices = $mysqli->query($query) or die($mysqli->error.__LINE__);
?>
答案 0 :(得分:1)
如上所述,使用SQL LIMIT语句将klausimai查询结果限制为10($ query =“SELECT * FROM klausimai
LIMIT 10”;):
<?php
//Set question number
$number = (int) $_GET['n'];
/*
* Get total questions
*/
$query = "SELECT * FROM `klausimai` LIMIT 10";
//Get result
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total = $results->num_rows;
/*
* Get Question
*/
$query = "SELECT * FROM `klausimai`
WHERE question_number = $number";
//Get result
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$question = $result->fetch_assoc();
/*
* Get Choices
*/
$query = "SELECT * FROM `atsakymai`
WHERE question_number = $number";
//Get results
$choices = $mysqli->query($query) or die($mysqli->error.__LINE__);
?>
答案 1 :(得分:1)
你的代码很好,但要打印10个直接从你的mysql数据库获取的随机问题,执行以下查询:
$query = SELECT * FROM `klausimai`
ORDER BY RAND()
LIMIT 10;
while(row=mysql_fetch_array($query) {
echo $row['question_feild'];
//Replace 'question_feild' it with your question_body column of your table
//assuming you have 2 choices for a particular question
echo $row['choice1']; // Same replace it with your choice/answer columns
echo $row['choice2']; // Same replace it with your choice/answer columns
}
答案 2 :(得分:0)
试试这个:
/*
* Get Questions
*/
$query = "SELECT * FROM `klausimai` ORDER BY RAND() LIMIT 10";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)){
echo "Question number " . $row["question_number"] . "<br/>";
echo "Choices of question are:<br/>";
/*
* Get Choices
*/
$query = "SELECT * FROM `atsakymai` WHERE `question_number` = " . $row["question_number"];
$result = mysqli_query($conn, $query);
$i = 1;
while($row2 = mysqli_fetch_assoc($result)){
echo $i.") ".$row2["choice_text"]."<br/>";
$i++;
}
}