PHP - 使用for循环自动显示序列号

时间:2017-12-08 15:56:52

标签: php

<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>

我想在表中自动显示获取结果的序列号。这里序列号正确显示前五个结果,如1,2,3,4,5行 但在第二页上,数字显示为8,9,10,6,7

我在哪里弄错了?我甚至试过while循环和forloop增量计数器。我使用Bootstrap数据表来显示数据库的结果。

2 个答案:

答案 0 :(得分:0)

$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++;
}

这对你有用。你需要在循环中获取结果才能解析它们。

答案 1 :(得分:0)

试试这个

你必须在while循环之外声明$i=1并在while循环中声明$i++。因此它将显示数据库中可用的行数。 你必须使用while循环设置while循环。

<?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>