你們好,我顧某人又回來了,最近學了一點PHP,而後就想寫個簡單小例子試試,因而就寫了一個相似於從題庫抽題的東西,大概就是先輸入須要抽題的數量,而後從數據庫中隨機抽取題目。
但願各位大佬輕噴。
假設我如今有這樣一個題庫:
啊?爲何要用英文?,由於我,,沒搞定編碼問題😭。
接着我來進行抽題:
這樣就隨機抽出了三道題目。php
如今來講說個人思路,但願各位大佬不吝賜教。
首先要實現這個功能,首先我須要三個頁面,一個是用戶輸入頁面input.html
,一個是後臺處理頁面select.php
,還有一個是錯誤警告頁面error.html
(若是用戶輸入爲空,或者輸入的抽題數量超過了題庫的數量那麼就報錯),而後是數據庫,數據庫分爲兩列,一列是question
,用來存放題目,另外一列是id
,用於標識question
。html
而後對用戶的輸入進行判斷:
mysql
input.html
頁面:sql
<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(); //關閉鏈接 ?>
各位大佬,若是大家不介意的話,我只想要一點流量(我的博客)。fetch