scan4jobs

How to display serial numbers in foreach loop in PHP?

Answered
0
0

How to display serial numbers in foreach loop in PHP?

 

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

<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>
  • You must to post comments
Best Answer
0
0

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>
  • You must to post comments
Best Answer
0
0
0

How about:

echo '<ul>';

$sn_count = 1;
foreach($urls as $url){
    echo '<li><span class="serial-number">'.$sn_count.'</span> '.$url .'</li>';
    $sn_count++;
}

echo '</ul>';

You can then style your serial numbers with the serial-number class.

  • You must to post comments
Showing 2 results
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website