在表格中显示记录

时间:2013-12-16 09:01:03

标签: php html mysqli

我的第一个PHP项目遇到了一些问题,我试图从MySQL数据库中获取数据(有3条记录)并将其显示在表格中。问题是它似乎只显示记录2和3,它跳过第一条记录。请参阅我的代码并在下面显示。

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM unitstats");

while($row = mysqli_fetch_array($result)) {
  echo "<table border='1' style='color:white'>
  <tr>
  <th>ID</th>
  <th>Name</th>
  </tr>";

  while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "</tr>";
  }
  echo "</table>";
}

enter image description here

3 个答案:

答案 0 :(得分:1)

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

echo "<table border='1' style='color:white'>
<tr>
<th>ID</th>
<th>Name</th>
</tr>";

$result = mysqli_query($con,"SELECT * FROM unitstats");

while($row = mysqli_fetch_array($result))
{
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "</tr>";
}
  echo "</table>";

基本上你不需要初始循环,这主要会导致一个问题,因为你会用第二个循环重新声明$row

答案 1 :(得分:1)

你正在使用两个while循环,这是不必要的使用代码

if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

      echo "</table>";


echo "<table border='1' style='color:white'>
<tr>
<th>ID</th>
<th>Name</th>
</tr>";
$result = mysqli_query($con,"SELECT * FROM unitstats");

while($row = mysqli_fetch_array($result))
  {


echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "</tr>";
}
  echo "</table>";

答案 2 :(得分:0)

只需删除外部while循环,然后使用:

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM unitstats");


echo "<table border='1' style='color:white'>
<tr>
<th>ID</th>
<th>Name</th>
</tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "</tr>";
}
echo "</table>";