php - 来自MySQL数据库的PHP POST循环

原文 标签 php mysql

我是php新手,我正在尝试构建一个php测试,阅读mysql数据库中的问题和答案。
到目前为止,我有以下代码:

require_once("scripts/connect_db.php");
session_start();
$_SESSION['Qid'] = 1;
if (!isset($_POST['answer'])){
    $Qid = $_SESSION['Qid'];
    echo $Qid;
    $stmt = $dbh->prepare("Select * FROM qtable WHERE id = ?");
    $stmt->bindParam(1, $Qid);
    $stmt->execute();
    $result = $stmt->fetchObject(); 
    echo $result->Q . "<br />";
    $stmt = $dbh->prepare("SELECT * FROM atable WHERE Qid = ? ORDER BY rand()");
    $stmt->bindParam(1, $Qid);
    $stmt->execute();
    $result = $stmt->fetchAll();
    echo "<form action=\"test1.php\" method=\"post\">";
    foreach ( $result as $row ) {
        if ( $row['correct'] == 1 ){
            echo "<input type=\"radio\" name=\"answer\" value=\"1\">" .$row['answer']."<br />";
        } else {
            echo "<input type=\"radio\" name=\"answer\" value=\"0\">" .$row['answer']."<br />";
        }
    }   
    echo "<input type=\"submit\" value=\"next\">";
    echo "</form>";     
}
else
{ 
    $Qid = $_SESSION['Qid'] + 1;
    echo $Qid;
    $stmt = $dbh->prepare("Select * FROM qtable WHERE id = ?");
    $stmt->bindParam(1, $Qid);
    $stmt->execute();
    $result = $stmt->fetchObject(); 
    echo $result->Q . "<br />";
    $stmt = $dbh->prepare("SELECT * FROM atable WHERE Qid = ? ORDER BY rand()");
    $stmt->bindParam(1, $Qid);
    $stmt->execute();
    $result = $stmt->fetchAll();
    echo "<form action=\"test1.php\" method=\"post\">";
    foreach ( $result as $row ) {
        if ( $row['correct'] == 1 ){
            echo "<input type=\"radio\" name=\"answer\" value=\"1\">" .$row['answer']."<br />";
        } else {
            echo "<input type=\"radio\" name=\"answer\" value=\"0\">" .$row['answer']."<br />";
        }
    }   
    echo "<input type=\"submit\" value=\"next\">";
    echo "</form>";
}

我的想法是每次按submit时将$_SESSION['Qid']增加1,这样我就可以循环访问数据库,但到目前为止,我只能转到第二行。有谁能帮我或给我指一个正确的方向,告诉我如何使用Jquery或AJAX。
谢谢

最佳答案

你继续重置$_SESSION['Qid'] = 1;
尝试

require_once("scripts/connect_db.php");
session_start();
//$_SESSION['Qid'] = 1;

if(!isset($_SESSION['Qid']) {
    $_SESSION['Qid'] = 1;
}

然后在接近结束时,添加以下内容以将计数器保存回会话:
$_SESSION['Qid'] = $Qid;

相关文章:

php - MySQL-null = 0的问题

php - PHP和Elasticsearch在返回的对象中包含得分/相关性

javascript - 将MySQL结果获取到路由文件

mysql - 如何在jasperreports中汇总一个月中的值(总和)(每个月应为前一个月的总和)

mysql - 具有单个UNIQUE约束指示符的MySQL列名称

php - Preg_match标识符

php - YouTube上。如何使用PHP上传视频

php - 当销售表数量增加时,可用数量列应自动减少

mysql - 不应该存在的“重复的列名”错误

php - UNION ALL内部的COUNT会导致跳过预期结果