Mysql
 sql >> Database >  >> RDS >> Mysql

Gestione del ciclo while e raggruppamento di valori PHP MySQL

Cerca di evitare mysql_* funzioni. Usa mysqli_* . Devi solo raggrupparli prima. Considera questo esempio:

<?php

$link = new mysqli('localhost', 'test', 'test', 'test');
$query = mysqli_query($link, 'SELECT * FROM author_master ORDER BY author_id');
$books = array();
while($row = $query->fetch_assoc()) {
    $books[$row['author_id']][] = $row;
}
?>

<table border="0" cellpadding="10">
    <thead>
        <tr>
            <th>Author ID</th>
            <th>Author Book</th>
            <th>Rating</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($books as $author_id => $values): ?>
            <tr>
                <td><?php echo $author_id; ?></td>
                <td><?php foreach($values as $author_book) {echo $author_book['author_book'] . '<br/>';} ?></td>
                <td><?php foreach($values as $author_book) {echo $author_book['rating'] . '<br/>';} ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>