I need to make php only show the last 10 news

Asked

Viewed 142 times

-1

<?php
    session_start();
    include "conexao.php";
    $sql = "SELECT * FROM noticia ORDER BY id DESC";
    $noticia = $conn->query($sql);
    $conn->close();
?>
<?php include "include/header.php" ?>
<?php
    if ($noticia->num_rows > 0) { 
    while($row = $noticia->fetch_assoc()) {
      ?>

    <div class="card text-white bg-secondary my-5 py-4 text-center">
      <div class="card-body">
        <p class="text-white m-0"></p>
      </div>
    </div>

    <!-- Content Row -->
    <div class="row">
      <div class="col-md-4 mb-5">
        <div class="card h-100">
          <div class="card-body">
            <h2 class="card-title"><?php echo "{$row['titulo']}";?></h2>
            <p class="card-text"><?php echo "{$row['data_noticia']}";?></p>
          </div>
          <div class="card-footer">
            <a class="btn btn-primary btn-sm" href="noticia.php?id="<?php.$row['id'].;?>> Noticia</a>
          </div>
        </div>
      </div>
      <!-- /.col-md-4 -->

    <?php
    }
    }
    ?>
<?php include "include/footer.php" ?>

I used that code, news comes in descending order, but I want you to show only the last 10

  • 2

    Just change the SQL query and add a limit. This question is about SQL, not about PHP or HTML.

  • I didn’t know it was about SQL, how do I change the query/

  • Thank you very much!

2 answers

4

Limiting your query would be enough:

SELECT * FROM noticia ORDER BY id DESC LIMIT 10;

2

Really the way @Ivan Ferrer answered already solves your question, another way to perform this check would be with:

SELECT * FROM noticia ORDER BY id DESC LIMIT 1, 10;
  • And why would that be another way if it’s the same thing?

Browser other questions tagged

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