Elankumaran
Elankumaran

Reputation: 11

PHP - Display Serial Numbers automatically using for loop

<thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
   <?php 

        $result = mysqli_query($connect,"SELECT * FROM movies ;")or die(mysqli_error());
        $rows = mysqli_fetch_array($result);
        ?>
        <tbody>

        <?php 
        $counter=0;                                                                                 
        foreach($result as $rows)
        {
        $counter=$counter+1;
        ?>
        <?php     echo "<tr><td>" . $counter . "</td><td>" . $rows['language'] . "</td><td>" . $rows['movie_name'] . "</td></tr>"; ?>
    <?php  } ?>
         </tbody>

I want to display serial numbers in the table automatically for the fetched results . Here the serial number displays correctly for the first five results like 1,2,3,4,5 rows but on the 2nd page the number shows like 8,9,10,6,7

Where i am making mistake ? I even tried while loop and forloop increment counter. Im using Bootstrap data table to display the results from database.

Upvotes: 1

Views: 11965

Answers (2)

Naren Verma
Naren Verma

Reputation: 2327

Try this

You have to declare the $i=1 outside of the while loop and $i++ inside the while loop. So it will display the number of rows available in the database. You have to use while loop instated of foreach.

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM movies";
$result = mysqli_query($conn, $sql);

//mysqli_close($conn);
?>

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<table>
<thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
        <tbody>
      <?php
      $i=1;
      if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($rows = mysqli_fetch_assoc($result)) {
            echo "<tr>
                  <td>" . $i . "</td>
                  <td>" . $rows['language'] . "</td>
                  <td>" . $rows['movie_name'] . "</td>
                 </tr>";
            $i++;
        }
    } else {
        echo "0 results";
    }
?>

         </tbody>
</table>
</body>
</html>

Upvotes: 0

pr1nc3
pr1nc3

Reputation: 8348

<?php
    $result = mysqli_query($connect,"SELECT * FROM movies");

    $counter=0; 
    while($rows = mysqli_fetch_array($result)){
    
    echo "<tr><td>" . $counter . "</td>
              <td>" . $result[$counter]['language'] . "</td>
              <td>" . $result[$counter]['movie_name'] . "</td>
          </tr>";
    $counter++;
    }
?>

This should work for you. You need to fetch the results inside a loop in order to parse them.

Upvotes: 2

Related Questions