0

The foreach prints out each of the headers, and I get all the accordions, but everything but the first accordion are empty. What am I missing?

$result2 = mysqli_query($con, "SELECT * FROM sections ORDER BY `order`");
    $sectionnames = array();
    while($row = mysqli_fetch_array($result2)) {
        $sectionnames[] = $row['sectionname'];
    }

    $result = mysqli_query($con,"SELECT * FROM faq ORDER BY `order`");

    foreach ($sectionnames as $sectionname) {
            echo '<h3 id="sectionname">' . $sectionname . '</h3>';
            echo '<div id="accordion">';
            while($row = mysqli_fetch_array($result)) {
                if ($sectionname == $row['section']) {
                    echo '<h3>' . $row['heading'] . '</h3>';
                    echo '<div>' . $row['content'] . '</div>';
                } 
           }
           echo '</div>';
    }

3 Answers 3

1

Without your schema I can't be sure, but it looks like faq is related to section by sectionname. If that's true, something like this:

foreach ($sectionnames as $sectionname) {
        echo '<h3 id="sectionname">' . $sectionname . '</h3>';
        echo '<div id="accordion">';
        $result = mysqli_query($con,"SELECT * FROM faq where section = '$sectionname' ORDER BY `order`");
        while($row = mysqli_fetch_array($result)) {   
           echo '<h3>' . $row['heading'] . '</h3>';
           echo '<div>' . $row['content'] . '</div>';    
       }
       echo '</div>';
}
Sign up to request clarification or add additional context in comments.

Comments

0
echo '<div id="accordion">';
while($row = mysqli_fetch_array($result)) 

This will effectively consume every row from your query result and put it inside the first accordion.

For every other $sectionname, your $result will already have been exhausted and will therefore generate empty accordions, since you do not realize any new queries.

2 Comments

so what do I need to do to fix it
This is normal behaviour. You're fetching data row by row from the resource. Once it's finished, resource pointer is at the end. That's why you have to reset it. What you can do instead is create an empty array before your while and inside of it do $data[] = $row. Your $data var will now contain all the results that you can reuse.
0

I just needed to add this code right before the while loop

mysqli_data_seek($result, 0);

1 Comment

That may work, but it's doing so by useless repeat scan over the result set as Arthur noted. You should let SQL do the work. Take a look at my answer for how to improve it more in that direction.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.