【问题标题】:PHP - Display Serial Numbers automatically using for loopPHP - 使用 for 循环自动显示序列号
【发布时间】:2017-12-08 15:56:52
【问题描述】:
<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 数据表来显示来自数据库的结果。

【问题讨论】:

  • 您的 foreach 应该循环通过 $rows,而不是 $result
  • mysqli_fetch_array 一次只返回一行。你需要一个while循环。此外,您在此处显示的代码,以及您所说的您看到的......不对齐。

标签: php


【解决方案1】:
<?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++;
    }
?>

这应该适合你。您需要在循环中获取结果才能解析它们。

【讨论】:

  • 我收到类似“通知:未定义变量:i”的错误。我应该在 while 循环中使用 forloop 吗?
  • 我想说的是$counter 不好,嵌套循环不是最好的做法,但如果它适用于您的大学项目,那为什么不呢。但请记住,如果您可以避免嵌套循环,请避免它们。
【解决方案2】:

试试这个

您必须在 while 循环外声明 $i=1 并在 while 循环内声明 $i++。因此它将显示数据库中可用的行数。 您必须使用 foreach 的 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>

【讨论】:

    猜你喜欢
    • 2017-01-27
    • 2019-12-26
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多