Display only one record with foreach

Asked

Viewed 1,361 times

1

I need help to display only one database record, follow 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 ):
?>

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

2 answers

4

If you want one, you don’t need foreach, just pick up 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 since $posts[0] until $posts[ultimo item], if you want only one, specify the first index, which is zero.

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

  • All right your thanks, I have another question take a look at the reply comment down there.

1


You can limit your query for a single result, thus the foreach will have only 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 then right away in your code give a 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; ?>
  • It worked here, but I also wanted to know if I could automatically delete an entry in PHP after the date has passed.

  • @Mateusjosépretti may be clearer?

  • I can, so look. After the date recorded in the database is passed by the current date, the system would delete the line that has the date exceeded. example: Line in DB: date: 11/01/2017 Current Day: 15/01/2017 The database should delete the data with the lower date of the current date in GMT-1 = 14/01/2017, if not understood question dnv kkkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.