display records in table

2019-03-04 13:20发布

问题:

I am having some trouble with my first PHP project, I am trying to get the data from MySQL database (Has 3 records) and display it in tables. Problem is it only seem to display records 2 and 3, it skips the 1st record. Please see my code and display below.

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>";
}

回答1:

you are using two while loop which is unnecessary use following code

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:

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

Basically you didn't need the initial loop, this would have mainly caused an issue because you would have been redeclaring $row with the second loop.



回答3:

Just remove your outer while loop and just use this:

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


标签: php html mysqli