mysqli_fetch_array 如何一次获取一行?

我的 php 代码如下: 这是测验的一部分,我通过 ajax jQuery 在 html 页面中显示一个问题和 4 个多项选择。我知道如何运行 while 循环并一个接一个地显示所有数据,但如何一次只显示一个问题?


所以在回答完一个问题后,我想查看下一个问题。是否可以运行一个计数器并一次拉出一个结果和下一个结果等等……?


<?php 

header("Access-Control-Allow-Origin: *");

require 'db.php';

// making empty variable

$createTable = "";


        $test_id=$_POST["test_id"];

        $sql=mysqli_query($con,"select * from mst_question where test_id='$test_id' ");

    $counter = 0;


while($row=mysqli_fetch_array($sql))

        {   

    $counter++;

        $createTable .= '<div class="text-subhead-2 text-center" style="background-color:#42A5F5">Question ';

        $createTable .= $counter;

        $createTable .= ' of 25</div>';

        $createTable .= '<div class="panel panel-default paper-shadow" data-z="0.5">';


        $createTable .= '<div class="panel-body">';

        $createTable .= '<p class="text-body-2">';

        $createTable .= $row['que_desc'];

        $createTable .= '</p>';

       $createTable .= '</div>';

        $createTable .= '</div>';


        $createTable .= '<div class="text-subhead-2 text-light">Your Answer</div>';

        $createTable .= '<div class="panel panel-default paper-shadow" data-z="0.5">';

        $createTable .= '<div class="panel-body">';

        $createTable .= '<div class="radio radio-success">';

        $createTable .= '<input type="radio" name="radio';

        $createTable .= $counter;

        $createTable .= '" id="radio1';

        $createTable .= $counter;

        $createTable .= '" value="';

        $createTable .= $row['ans1'];

        $createTable .= '" >';

        $createTable .= '<label for="radio1';

        $createTable .= $counter;

        $createTable .= '">';

        $createTable .= $row['ans1'];

        $createTable .= '</label>';

        $createTable .= '</div>';

   

拉莫斯之舞
浏览 152回答 1
1回答

呼啦一阵风

首先,您的代码很危险,因为可以通过 sql 注入攻击。您始终应该使用参数绑定。最简单的方法是传递存储在 mst_question 中的问题的 id,并通过 WHERE 子句(如 test_id)选择一个。//...$test_id=$_POST["test_id"];$questionId = filter_var($_POST['question_id'],FILTER_VALIDATE_INT);if (!$questionId){&nbsp; &nbsp;die('done');}$stmt= mysqli_prepare($con,"select * from mst_question where test_id='$test_id' AND id=?");mysqli_stmt_bind_param(**$stmt**, 'd',$questionId);mysqli_stmt_execute(**$stmt**);// work with $stmt.&nbsp;// f.e. your loop but now there will be only one executionmysqli_stmt_close($stmt);//...$createTable .= '<input type="hidden" name="nextQuestionId" value="'.$nextQuestionId.'"/>';//...使用输入字段,您将返回下一个问题的 ID,该 ID 可以在 JavaScript 代码中的 url 参数中传递。如果您担心测验作弊者,可以通过散列 nextQuestionId 来提高安全性。//...$stmt = mysqli_prepare($con,"select * from mst_question where test_id='$test_id' AND sha1(CONCAT('slat_',id))=?");//...$createTable .= '<input type="hidden" name="nextQuestionId" value="'.sha1('salt_'.$nextQuestionId).'"/>';//...这不是最好的解决方案,但需要对代码进行最少的更改。我想建议切换到 PDO - 与数据库交互的非常友好和强大的方式。看一个例子。
打开App,查看更多内容
随时随地看视频慕课网APP