dqwh1119 2016-10-23 14:30
浏览 22
已采纳

Php pdo用序列迭代

i want to display question and answers with sequence(first:question then answers) how is it possible?

$servername = "localhost";
$username = "someone";
$password = "someonepassword";
$dbname = "quiz_app";

$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$statement = $pdo->prepare("SELECT * FROM question");
$statement2 = $pdo->prepare("SELECT a.id as answer_id, a.*, 
                                    q.id as question_id, q.* 
                            FROM answer a 
                                inner join question q on a.question_id = q.id");


$statement->execute();
$statement2->execute();


$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$result2 = $statement2->fetchAll(PDO::FETCH_ASSOC);

$i=0;
foreach ($result as $row) {
  $i++;
  echo "<h5>".$i.'.'.$row['question_text']. "</h5>";
    foreach ($result2 as $row2) {
      echo "<input name='group". $row2['id'] ."' type='radio' id='". $row2['answer_id'] ."' />" . "<label for='". $row2['answer_id'] ."'>".$row2['answer_text']."</label>";
     }
  echo "<br>";
 }

In this code questions and answers are ordered differently(all questions together and after them answers) how can i fix it?

  • 写回答

2条回答 默认 最新

  • doutan6286 2016-10-23 14:43
    关注

    Think more logically about the data you are processing. The first query is totally unnecessary, everything you need is in the second query. Just order that by q.id and a.id

    $stmt = $pdo->prepare("SELECT q.*,q.id as qid,
                                  a.*, a.id as aid
                            FROM question q 
                                inner join answer a on a.question_id = q.id
                            ORDER BY qid, aid");
    
    $q_and_a = $statement->fetchAll(PDO::FETCH_ASSOC);
    
    $last_qid = NULL;
    foreach ( $q_and_a as $i => $row) {
        if ( $last_qid == $row['qid'] ) {
            // we are starting a new question
            echo "<h5>{$row['question_text']}</h5>";
            $last_qid = $row['qid'];
        }
        // hear we are processing all the answer to the question
        echo "<input name='group{$row2['qid']}' type='radio' id='{$row['aid']}'/>" 
            . "<label for='{$row['aid']}'>{$row['answer_text']}</label>";
    }
    

    Not sure if I got the question id and answer id info in the right place in the output, but hopefully this will give you a nudge in the right direction and you can fix any little issues yourself

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路