Listing data separating them by date

1

I have the following structure:

I want to list all products separated by date. Type, date products such are in a table, since another date is in another table, and so on ... All this on the same page.

    
asked by anonymous 20.11.2015 / 19:18

1 answer

1

The following form attempts to minimize the number of queries to the database, with only two queries remaining, and for the rest PHP is responsible.

The logic is nothing more than to get the dates that will be listed sorted, and get the list of all products ordered by the dates as well. Then scroll through the list of dates, and for each date you go through the list of products removing each item after submitting, until the date change. When you change the table it is finished and it moves on to the next date.

<?php
// Obtendo as compras ordenadas pela data
$sqlCompras = '
    SELECT
        DATE_FORMAT(c.'data', '%d-%m-Y') as "data",
        c.'produtoNome',
        c.'preco'
    FROM 'compras' as c
    ORDER BY
        DATE_FORMAT(c.'data', '%d-%m-Y') ASC,
        c.'produtoNome' ASC
';
$resCompras = $conexao->prepare($sqlCompras);
$resCompras->execute();
$compras = $resCompras->fetchAll();

// Obtendo todas as datas disponíveis
$sqlDatas = '
    SELECT
        DATE_FORMAT(c.'data', '%d-%m-Y') as "data"
    FROM 'compras' as c
    GROUP BY BY c.'data'
    ORDER BY
        DATE_FORMAT(c.'data', '%d-%m-Y') ASC,
';
$resDatas = $conexao->prepare($sqlDatas);
$resDatas->execute();
$datas = $resDatas->fetchAll();
?>

<?php foreach ($datas as $data) { ?>
<table>
    <caption><?php echo $data['data'] ?></caption>
    <thead>
        <tr>
            <th scope="col">Nome do produto</th>
            <th scope="col">Preço</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($compras as $key => $compra) { ?>
            <?php
            // Percorre os produtos até encontrar uma data diferente,
            // quando encontrar, quebra o laço de repetição e passa para a
            // próxima data.
            if( $compra['data'] != $data['data']) {
                break;
            } else {
            ?>
                <tr>
                    <td><?php echo $compra['produtoNome'] ?></td>
                    <td><?php echo $compra['preco'] ?></td>
                </tr>
                <?php unset($compras[$key]) ?>
            <?php } ?>
        <?php } ?>
    </tbody>
</table>
<?php } ?>
    
20.11.2015 / 20:37