【问题标题】:While loop only display first row from databaseWhile 循环仅显示数据库中的第一行
【发布时间】:2019-09-27 14:35:49
【问题描述】:

我知道这是一个超级基本的问题,但我一整天都找不到答案。 我试图在一个表中显示我所有的数据库行,而我的 while 循环只显示第一行。

我尝试将 while 循环的条件更改为“mysqli_fetch_array”,然后甚至第一行都没有出现。

echo "<table>";
    echo "<tr>
        <th>Match_Id</th>
        <th>Home_Team</th> 
        <th>Away_Team</th>
        <th>Result</th>
        <th>season</th> 
        <th>notes</th>
        <th>Goals_Sum</th>
      </tr> ";


     $sql = "SELECT * FROM PremierLeague";
   `enter code here`  $result = sqlsrv_query($conn, $sql);

 while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
     echo "<tr>";
     $id = $row['id'];
     echo "<td>$id</td>";
     $Home = $row['Home'];
     echo "<td>$Home</td>";
     $Away = $row['Away'];
     echo "<td>$Away</td>";
     $result = $row['result'];
     echo "<td>$result</td>";
     $season = $row['season'];
     echo "<td>$season</td>";
     $notes = $row['notes'];
     echo "<td>$notes</td>";
     $home_goals= $row['home_goals'];
     $away_goals= $row['away_goals'];
     $GoalSum = $home_goals+$away_goals;
     echo "<td>$GoalSum</td>";
     echo "</tr>";
 }
  echo "</table>";

预期结果:包含数据库中所有行的表。 实际结果:只有数据库的第一行

【问题讨论】:

  • 你为什么首先使用while循环?这是为循环设计的问题。
  • 你能举个例子,我如何用 for 循环做到这一点?
  • 您的代码有语法错误。您粘贴正确了吗?

标签: php html mysql sql


【解决方案1】:
echo "<table>";
    echo "<tr>
        <th>Match_Id</th>
        <th>Home_Team</th> 
        <th>Away_Team</th>
        <th>Result</th>
        <th>season</th> 
        <th>notes</th>
        <th>Goals_Sum</th>
      </tr> ";


     $sql = "SELECT * FROM PremierLeague";
  $result = sqlsrv_query($conn, $sql);

 while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
            $id = $row['id'];
          $Home = $row['Home'];
          $Away = $row['Away'];     
        $result = $row['result'];
       $season = $row['season'];
       $notes = $row['notes'];
     $home_goals= $row['home_goals'];
     $away_goals= $row['away_goals'];
     $GoalSum = $home_goals+$away_goals;



 echo $output.="<tr>
                 <td>$id</td>
                 <td>$Home</td>
                 <td>$Away</td>
                 <td>$result</td>
                 <td>$season</td>
                 <td>$notes</td>
                 <td>$GoalSum</td>
                </tr>";
 }
  echo "</table>";

【讨论】:

  • 我做了,但这是一个错误,所以我删除了它。为此事道歉。但是,我看不出你的提议与 OP 有什么不同……
  • 复制了你的代码,仍然只显示一行。
  • while循环中的条件ok吗?
  • 从 while 循环中删除 SQLSRV_FETCH_ASSOC 并尝试一下。
  • 没有改变任何东西
【解决方案2】:

您的代码示例乍一看很干净,但这仍然让我想起两种不同的可能性:

  • 您的表只包含一行。这很愚蠢,但必须先检查。好吧,我想你做到了;
  • 一个无关的分号“;”在while() 条件后被遗忘:
    while($res=fetch(…));
    {
        display something…
    }

在这种情况下,循环将迭代直到数据集结束,然后将输入大括号中的块(假定为孤立块),显示变量中剩余的内容。但在这种情况下,您应该得到查询的最后行,而不是第一行。

【讨论】:

  • 1.我的表包含多于一行。 2.确定它显示第一行,所以它不是分号,即使我尝试添加它然后没有出现任何行。
猜你喜欢
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2014-11-03
  • 2023-03-16
相关资源
最近更新 更多