gpt4 book ai didi

php - 从数据库中选择随机列

转载 作者:行者123 更新时间:2023-11-29 05:15:44 25 4
gpt4 key购买 nike

我有一个表question_bank,表的结构是

question_id | question | a | b | c| d | correct_ans

我可以向用户展示随机问题。但是有什么方法可以选择随机列吗?我也想洗牌问题的选项。我在做

 {
$query = "SELECT * from question_bank where exam_name='$subject' and exam_class_id='$class_id' order by rand() limit 4";


$result = mysqli_query($connection, $query);

$all = array();
while ($row = mysqli_fetch_assoc($result))
{
$all[] = $row;
}

$_SESSION['result'] = $all;
?>
<form action="result.php" name="form1" method="post" id="quiz">
<?php
echo "<input type='text' name='subject_id' value='$class_id'>";
echo "<input type='text' name='subject_name' value='$subject'>";
foreach ($_SESSION['result'] as $read_all_data)
{
$id=$read_all_data['id'];
echo $read_all_data['question']."</br>";

$random_option=array($read_all_data['a'],$read_all_data['b'],$read_all_data['c'],$read_all_data['d']);
$random_keys=array_rand($random_option,4);


echo "A:<input type ='radio' value ='a' name='$id' >".$random_option[$random_keys[0]]."</br>";
echo "B:<input type ='radio' value ='b' name='$id' >".$random_option[$random_keys[1]]."</br>";
echo "C:<input type ='radio' value ='c' name='$id' >".$random_option[$random_keys[2]]."</br>";
echo "D:<input type ='radio' value ='d' name='$id' >".$random_option[$random_keys[3]]."</br>";

}

?>
<input type='submit' value='submit' name='submit1'> </form>

最佳答案

我认为我们需要在开始之前重新考虑一下。拿一张纸和一支笔。想想你想做什么,然后用伪代码写下来。如果我没看错的话,这似乎是一些问题/答案库。

所以我会这样做。

    $query = "SELECT * from question_bank where exam_name='$subject' and exam_class_id='$class_id' order by rand() limit 4";


$result = mysqli_query($connection, $query);


$all = array();
while ($row = mysqli_fetch_assoc($result))
{
$questions = array();
$questions[] = array('a',$row['a']);
$questions[] = array('b',$row['b']);
$questions[] = array('c',$row['c']);
$questions[] = array('d',$row['a']),


$questions = shuffle($questions);



echo "A:<input type ='radio' value ='$question[0][0]' name='$row['question_id]' >".$question[0][1]."</br>";
echo "B:<input type ='radio' value ='$question[1][0]' name='$row['question_id]' >".$question[1][1]."</br>";
echo "C:<input type ='radio' value ='$question[2][0]' name='$row['question_id]' >".$question[2][1]."</br>";
echo "D:<input type ='radio' value ='$question[3][0]' name='$row['question_id]' >".$question[3][1]."</br>";



}

关于php - 从数据库中选择随机列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com