打印表行时出错

时间:2013-05-29 09:09:45

标签: php

我正在尝试使用我从数据库中提取的数据打印出一个表。这是代码

<?php
  $host = "localhost";
  $user = "root";
  $pass = "";
  $databaseName = "caliban";
  $tableName = "caliban";
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);
  $result = mysql_query("SELECT * FROM $tableName");            //query
  $array = mysql_fetch_assoc($result);                          //fetch result   
  //--------------------------------------------------------------------------
  // 3) echo result as json
  //--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName");            //query 

$rows = Array();
$i=0;
while($row = mysql_fetch_assoc($result)){
        //array_push($rows, $row);
      $rows[$i++] = $row;
}
for($j=0;$j<count($rows); $j++){
      echo
      "<table><tbody><tr id='$rows[$j]['id']'>
<td><input type='checkbox' /></td>
<td>$rows[$j]['firstname']</td>
<td>$rows[$j]['lastname']</td>
<td>$rows[$j]['city']</td>
<td>$rows[$j]['continent']</td>
</tr></tbody></table>";
}
?>

错误重复8次,因为这些是我所拥有的总行数。

3 个答案:

答案 0 :(得分:1)

你为什么这么复杂?

请看一下本教程: http://php.net/manual/en/function.mysql-fetch-assoc.php

也许您也会考虑在不推荐使用MySQL时切换到MySQLD

答案 1 :(得分:0)

$rows = Array();
$i = 0;
echo "<table><tbody>";
while($row = mysql_fetch_assoc($result)) {
  extract($row);
  ?>
  <tr id="<?php echo $id ?>" >
        <td><input type=checkbox /></td>
        <td><?php echo $firstname ?></td>
        <td><?php echo $lastname ?></td>
        <td><?php echo $city ?></td>
        <td><?php echo $continent ?></td>
      </tr>
      <? }

echo "</tbody></table>";

答案 2 :(得分:0)

这就是我修复它的方式

<?php
  $host = "localhost";
  $user = "root";
  $pass = "";
  $databaseName = "caliban";
  $tableName = "caliban";
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);
  $result = mysql_query("SELECT * FROM $tableName");            //query
  $array = mysql_fetch_assoc($result);                          //fetch result   
  //--------------------------------------------------------------------------
  // 3) echo result as json
  //--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName");            //query 

$rows = Array();
$i=0;
while($row = mysql_fetch_assoc($result)){
        //array_push($rows, $row);
      $rows[$i++] = $row;
}
for($j=0;$j<count($rows); $j++){
$id = $rows[$j]['id'];
$firstname = $rows[$j]['firstname'];
$lastname = $rows[$j]['lastname'];
$city = $rows[$j]['city'];
$continent = $rows[$j]['continent'];
      echo 
      "<table><tbody><tr id='$id'>
<td><input type='checkbox' /></td>
<td>$firstname</td>
<td>$lastname</td>
<td>$city</td>
<td>$continent</td>
</tr></tbody></table>";
}
?>