Troutfisher
Troutfisher

Reputation: 69

While loop inside while loop returns only first row

I'm trying to make array filled with different objects. I have set of pages and set of questions. Pages are groups and questions belongs to them.

I want to query first pages, then find out how many questions are within. After that create object for each question and append them into specific pages.

// first get pages so we get grouping and order
$getPages = $conn->prepare("SELECT * FROM pages WHERE event_id = :event_id ORDER BY page_order ASC");
$getPages->bindParam(":event_id", $_SESSION['event_id']);
$getPages->execute();
$pageCount = $getPages->rowCount();
$pages = array();

// get pages
while ($row = $getPages->fetch()) {
    $page = array();
    $page['id'] = $row['id'];
    $page['order'] = $row['page_order'];

    // query for that page
    $stmt = $conn->prepare("SELECT * FROM questions WHERE page_id = :page_id");
    $stmt->bindParam(":page_id", $page['id']);
    $stmt->execute();
    while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];
        // push question into questions
        $page['questions'] = $question;
    }

    // push page into pages
    $pages[] = $page;
}

//print pages
echo json_encode($pages);

But sadly it only returns one row for each page...

Javascript object

Upvotes: 0

Views: 697

Answers (1)

B. Desai
B. Desai

Reputation: 16436

It's because your question overwrites each time. Change your code like below

<?php
$page['questions'] = array();
 while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];

        // push question into questions
        $page['questions'][] = $question;        
    }

Upvotes: 3

Related Questions