Display only one record with the foreach

0

I need help to display a record of the database, following code:

<?php
    $posts  = DBRead( 'posts', "WHERE categoria = 3 AND status = 1 ORDER BY data_numero ASC" );

    if( !$posts )
        echo '<h2>Nenhuma Corrida Registrada!</h2>';
    else
        foreach ( $posts as $post ):
?>

I would need to make the foreach return the with the smallest date and only one to insert into a BOX.

    
asked by anonymous 15.01.2017 / 20:19

2 answers

0

You can limit your query to a single result, so the foreach will only have one iteration.

<?php
    $posts  = DBRead( 'posts', "WHERE categoria = 3 AND status = 1 ORDER BY data_numero ASC LIMIT 1" );

    if( !$posts )
        echo '<h2>Nenhuma Corrida Registrada!</h2>';
    else
        foreach ( $posts as $post ):
?>

Or, soon afterwards, in your code give break

<?php
    $posts  = DBRead( 'posts', "WHERE categoria = 3 AND status = 1 ORDER BY data_numero ASC" );

    if( !$posts )
        echo '<h2>Nenhuma Corrida Registrada!</h2>';
    else
        foreach ( $posts as $post ):
?>
Dados do post: <?=$post?>
<?php break; ?>
<?php endforeach; ?>
    
15.01.2017 / 20:29
4

If you want one, you do not need foreach , just grab the index:

<?php
    $posts = DBRead('posts', "WHERE categoria = 3 AND status = 1 ORDER BY data_numero ASC");

    if( !$posts ) {
        echo '<h2>Nenhuma Corrida Registrada!</h2>';
    } else {
        $post = $posts[0]; // Pega o primeiro, sem precisar de foreach
    }
?>

The foreach iterates the variable from $posts[0] to $posts[ultimo item] , I do not know if you want one, it specifies the first index, which is zero.

If there are many items returned originally, you can limit the search with a LIMIT 1 at the end of query as commented by @gmsantos. This will not affect the on-screen output with the current solution, but will save unnecessary data transmission.

    
15.01.2017 / 20:27