66

PHP实现类似题库抽题效果

 5 years ago
source link: http://www.gubeiqing.cn/2018/10/06/php05/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PHP菜鸟

大家好,我顾某人又回来了,最近学了一点PHP,然后就想写个简单小例子试试,于是就写了一个类似于从题库抽题的东西,大概就是先输入需要抽题的数量,然后从数据库中随机抽取题目。

希望各位大佬轻喷。

假设我现在有这样一个题库:

fAjauyr.jpg!web

啊?为什么要用英文?,因为我,,没搞定编码问题:sob:。

接着我来进行抽题:

riuY7bA.jpg!webbURBBvi.jpg!web

这样就随机抽出了三道题目。

现在来说说我的思路,希望各位大佬不吝赐教。

首先要实现这个功能, 首先 我需要三个页面,一个是用户输入页面 input.html ,一个是后台处理页面 select.php ,还有一个是错误警告页面 error.html (如果用户输入为空,或者输入的抽题数量超过了题库的数量那么就报错), 然后 是数据库,数据库分为两列,一列是 question ,用来存放题目,另一列是 id ,用于标识 question

然后对用户的输入进行判断:

rANzquu.jpg!web

input.html 页面:

<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <form action="select.php" method="get">
        请输入要随机生成的题数:<input type="text" name="input" />
        <input type="submit" name="Submit" value="提交" />
    </form>
</html>

error.html 页面:

<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <p>您的输入有误,请重新输入!</p>
</html>

select.php 页面:

<?php
    header("Content-type:text/html;charset=utf8");
    $connect=new mysqli('localhost','wy','000000','test');
    if(!$connect){
        die("数据库连接失败!");
    }                           //连接数据库
    $sql="select id from test";
    $result=$connect->query($sql);
    $array=array();
    $i=0;
    while($row=$result->fetch_row()){
        foreach($row as $val){
            $array[$i]=$val; 
            $i ++;
        }
    }                          //将题目id存放进一个数组array
    $input=$_GET['input'];    //接受用户的输入
    if(empty($input) || $input>count($array)){  //判断用户的输入是否为空或输入大于题库数量
        header("Location:error.html");    //输入有误重定向到错误提示页面
    }else{
        shuffle($array);    //将存放题目id的数组进行随机排序
        $k=0;               //用于取出rand数组中question时的id
        for($j=0;$j<$input;$j++){
            $rand=array_slice($array,0,$input);     //从数组的第一个数开始,取出用户输入数量个id存放进一个数组
            $sql2="select * from test where id='{$rand[$k]}'";  //查找rand数组中每一个id对应的question
            $result2=$connect->query($sql2);    //存放mysql语句返回的结果集
            while($row2=$result2->fetch_assoc()){
                echo $row2['question'];     //返回question对应的内容
                echo '<br />';
            }
            $k++;
        }
        $result2->free();   //释放内存
    }
    $result->free();        //释放内存
    $connect->close();      //关闭连接
?>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK