1

I am writing a simple page that has a table. It is necessary to display the first five rows of the table. But for some reason, the last five rows of the table are displayed. How to display the first five rows of a table?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
            <style type="text/css">
                table {
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid black;
}
            </style>
    </head>
    <body>
        <?php
            $host = 'localhost';
            $database = 'books'; 
            $user = 'root'; 
            $password = 'root'; 
            $link = mysqli_connect($host, $user, $password, $database) 
                or die("Error " . mysqli_error($link)); 
            $query ="SELECT * FROM Book";
            $result = mysqli_query($link, $query) or die("Error " . mysqli_error($link)); 
            if($result)
            {
                $rows = mysqli_num_rows($result); 
                echo "<table>
                        <tr>
                            <th>bookid</th>
                            <th>Bookname</th>
                            <th>Authorid</th>
                        </tr>";
                for ($i = 0 ; $i < $rows ; ++$i)
                {
                    $row = mysqli_fetch_row($result);
                    echo "<tr>";
                    while ($row = mysqli_fetch_row($result)) 
                        {
                        echo "<tr>";
                            for ($j = 0 ; $j < 3 ; ++$j) 
                            echo "<td>$row[$j]</td>";
                        echo "</tr>";
                        }
                }
                echo "</table>";
                mysqli_free_result($result);
            }          
            mysqli_close($link);
        ?>
    </body>
</html>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161

3 Answers3

2

Try using this query

SELECT * FROM books ORDER BY id DESC LIMIT 1
Bhavin Kalal
  • 204
  • 1
  • 2
  • 13
0

Change your SQL request to

SELECT TOP 5 * FROM Book
Jérémy
  • 223
  • 2
  • 12
0

Try to add LIMIT 5 to your query. LIMIT X returns the first X rows from a table. If you want more pages, you can also use LIMIT in a combination with OFFSET, e.g. LIMIT 5 OFFSET 5 for the second page.

$query ="SELECT * FROM Book LIMIT 5";