在HTML表格中打印查询

时间:2015-02-20 17:47:13

标签: php mysql

我只是想知道是否有人能够帮助我解决我一直遇到的问题。我试图将mysql查询中的数据打印到html表中。我使用嵌套的for循环,我几乎就在那里。我似乎无法弄清楚如何打印多行结果。我现在的代码是:

$query = "select TeacherName, Age, Subject from Teacher WHERE schoolcode =" . $schoolcode; // Specifying the query and using the variable school code from the frontend HTML form to make it reusable

$result = mysqli_query($con, $query) or die("Invalid query"); //Running the query and storing it in result
$numrows = mysqli_num_rows($result);  // gets number of rows in result table
$numcols = mysqli_num_fields($result);   // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$row = mysqli_fetch_array($result);

print "<table border=1><tr>";
for($x=0;$x<$numcols;$x++){
print "<th>" . $field[$x]->name . "</th>";
}
print "</tr>";

for($j=0; $j<$numrows; $j++) {   // for loop goes round until there are no rows left
 print "<tr>";
     for ($k=0; $k<$numcols; $k++) {    //  goes around until there are no columns left
        print "<td>" . $row[$k] . "</td>"; //Prints the data
  }
   print "</tr>";
}

print "</table>";

mysqli_close($con); 
 ?>

代码几乎可以工作,并打印出正确结果的html表。问题是它打印出一行结果,然后在下一行重复同一行结果,而不是打印我想要的下一行结果。任何人都可以帮我解决这个问题吗?

非常感谢

3 个答案:

答案 0 :(得分:0)

试试这个。

while ($row = mysqli_fetch_array($result)) {
  echo '<tr>';
  for ($k=0; $k<$numcols; $k++) {    //  goes around until there are no columns left
        print "<td>" . $row[$k] . "</td>"; //Prints the data
  }
  echo '</tr>';
}

答案 1 :(得分:0)

你可以这样做

 <table>
 <Tr><td>Teacher Name</td></tr>
 <?php 
 while($row = mysqli_fetch_assoc($result))
{
   ?>
    <Tr><td><?=$row['TeacherName']?><td><tr>
  <?php
}
 ?>  
</table>

更干净的代码和更简单的方法

答案 2 :(得分:0)

只需尝试一下就可以了:

      $query = "select TeacherName, Age, Subject from Teacher WHERE schoolcode =" . $schoolcode;
        $result = mysqli_query($con, $query) or die("Invalid query");
    $row = mysqli_fetch_array($result);

    <table>
     <tr>
    <td>Teacher Name</td>
<td>Age</td>
<td>Subject</td>
    </tr>
     <?php 
     do
    {
       ?>
        <tr>
    <td><?php echo $row['TeacherName']; ?><td>
    <td><?php echo $row['Age']; ?><td>
    <td><?php echo $row['Subject']; ?><td>
    <tr>
      <?php
    }while($row = mysqli_fetch_array($result));
     ?>  
    </table>