简体   繁体   中英

Foreach list of mysql query result

I am trying to list down list of books grouped by author and populate the result in a radio button so that user will be able to select book belonged to different author. I manage to get the result and display the list like how I wanted it to be, but the radio button having the same name which making the user to only able to select one book even though the author is different.

My database table data looked something like this :

id  author  books
1  Author A  Book1
2  Author A  Book2
3  Author B  Book3

My current coding is as follow :

$sql = "SELECT author, GROUP_CONCAT(books SEPARATOR ',') as books FROM library GROUP BY author";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $books = explode(',',$row['books']);

        $i = 1;
        echo '<ul class="list-unstyled subjects">';
        echo '<li class="bordered" style="width: 30%;">'.$row['author'].'</li>';
        echo '<li class="bordered">';
        echo '<ul><li><input name="books" type="radio" value="" checked>N/A</li></ul>';

        foreach ($books as $book) {
            echo '<ul>';
            echo '<li><input name="books" type="radio" value="'.$book.'" />'.$book.'</li>';
            echo '</ul>';
        }

        echo '</li>';
        echo '</ul>';
        $i++;
    }
}

$sql = NULL;

So I am trying to put numbering at every end of the radio button name using the variable $i but it will make all the radio button to have a different name. I want to make it having same name for every group of author.

You're setting $i back to 1 for each author. You need to initialize it before the while loop.

if ($result->num_rows > 0) {
    $i = 1;
    while($row = $result->fetch_assoc()) {
        $books = explode(',',$row['books']);

        echo '<ul class="list-unstyled subjects">';
        echo '<li class="bordered" style="width: 30%;">'.$row['author'].'</li>';
        echo '<li class="bordered">';
        echo '<ul><li><input name="books$i" type="radio" value="" checked>N/A</li></ul>';

        foreach ($books as $book) {
            echo '<ul>';
            echo '<li><input name="books$i" type="radio" value="'.$book.'" />'.$book.'</li>';
            echo '</ul>';
        }

        echo '</li>';
        echo '</ul>';
        $i++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM