I.Jokhadze I.Jokhadze - 1 month ago 7
PHP Question

Php pdo iterate with sequence

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?

Answer

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

Comments