我正在创建一个PHP / MSQL应用程序,它基本上是一个在线测验,用户将在内部为一个实例启动测验,从db-table中检索30个问题并存储在会话中。我的数据库表有 qid,question,op1,op2,op3,op4,ans,category 作为列(因为每个问题应该有4个选项和一个答案)。 我想检索存储在特定类别表中的所有(对于实例30)问题,并使用一些将它们保存在会话变量中作为二维/三维关联数组循环说while()/ for()等。
我写的脚本是,
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$sql= "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result) && $i<=$found) {
$_SESSION["$i"]= array(
"question"=>$que['question'],
"op1"=>$que['op1'],
"op2"=>$que['op2'],
"op3"=>$que['op3'],
"op4"=>$que['op4'],
"ans"=>$que['ans']
);
$i++;
}
echo $_SESSION["$i"]; // echo-ing some session variable
}
mysql_close($dbc);
我还使用下面给出的脚本来提前做同样的事情,但没有成功 -
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$result1 = mysql_query($sql) or die(mysql_error());
$_SESSION['que'][][]=array();
while ($que= mysql_fetch_assoc($result1) && $i<=$found) {
$_SESSION['que'][$i]['question']=$que['question'];
$_SESSION['que'][$i]['op1']=$que['op1'];
$_SESSION['que'][$i]['op2']=$que['op2'];
$_SESSION['que'][$i]['op3']=$que['op3'];
$_SESSION['que'][$i]['op4']=$que['op4'];
$_SESSION['que'][$i]['ans']=$que['ans'];
$i++;
}
}
mysql_close($dbc);
最后我可以使用以下代码执行此操作 -
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$result1 = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result1) && $i<=$found) {
$str="que".$i;
$_SESSION[$str]['qno']=$i;
$_SESSION[$str]['question']=$que['question'];
$_SESSION[$str]['op1']=$que['op1'];
$_SESSION[$str]['op2']=$que['op2'];
$_SESSION[$str]['op3']=$que['op3'];
$_SESSION[$str]['op4']=$que['op4'];
$_SESSION[$str]['ans']=$que['ans'];
$_SESSION[$str]['opt']="0";
$i++;
}
}
mysql_close($dbc);
答案 0 :(得分:1)
试试这个。
require 'connection.php';
session_start();
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i=1;
$sql= "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result) && $i<=$found) {
$_SESSION[$i]= array(
"question"=>$que['question'],
"op1"=>$que['op1'],
"op2"=>$que['op2'],
"op3"=>$que['op3'],
"op4"=>$que['op4'],
"ans"=>$que['ans']
);
}
print_r($_SESSION[$i]);
$i++;
}
mysql_close($dbc);