2016-01-01 52 views
-1

我一直在研究将sql数据打印到表中的项目。最近,我在桌上遇到了问题。这段代码应该做的是输出从MySQL查询结果的表,但它所有的输出是一样的东西:PHP HTML表格显示为空

项目1                                                                                            项目1

出于某种原因,离开所有其他领域的空白。这里是我的代码:

$table = "<table class='TestTable'><tr class='tr'>"; 
while($row = mysql_fetch_assoc($result)){ 
    $table .= "<th class='th'>"; 
    $table .= $row['NameOfItem']; 
    $table .= "</th>"; 
} 
$table .= "</tr><tr class='tr'>"; 
while ($row = mysql_fetch_assoc($result)){ 
    $table .= " 
     <td class='td'>Minimum Bid: <b>"; 
     $table .= $row['MinBid']; 
     $table .= "</b></td>"; 
} 
$table .= "</tr><tr class='tr'>"; 
while ($row = mysql_fetch_assoc($result)){ 
    $table .= "<td class='td'>Current Bid: <b>"; 
     $table .= $row['CurrentBid']; 
     $table .= "</b></td>"; 
} 
$table .= "</tr><tr class='tr'>"; 
while ($row = mysql_fetch_assoc($result)){ 
    $table .= "<td class='td'>Sold By: <b>"; 
     $table .= $row['SoldBy']; 
     $table .= "</b></td>"; 
} 
$table .= "</tr><tr class='tr'>"; 
while ($row = mysql_fetch_assoc($result)){ 
    $table .= "<td class='td'>Time Left: <b>"; 
     $table .= printf('%d days, %d hours, %d minutes left', $diff->d, $diff->h, $diff->i); 
     $table .= "</b></td>"; 
} 
$table .= "</tr></table>"; 
echo $table; 

当我查看源代码,我得到:

<table class='TestTable'> 
    <tr class='tr'> 
     <th class='th'>Item1</th> 
     <th class='th'>Item1</th> 
    </tr> 
    <tr class='tr'></tr> 
    <tr class='tr'></tr> 
    <tr class='tr'></tr> 
    <tr class='tr'></tr> 
</table> 
+0

RTM:[mysql_fetch_assoc](http://php.net/manual/en/function.mysql-fetch-assoc.php):_返回与获取的行对应的字符串的关联数组,**或FALSE if没有更多的行。** _所有的行都在第一个'while'循环中读取......所以在下一个'while'时,没有更多的行要读取...... – FirstOne

+0

呃,我认为这里有问题。一旦在第一个循环中迭代了记录集,您需要将记录集指针重新倒回第一行。为什么这么多循环? – RamRaider

+0

你只能做*一次*'while($ row = mysql_fetch_assoc($ result))''。之后,你在$ result的最后,因此没有更多的行要返回。也更新到msqli或pdo! msql_函数已被弃用 – Jeff

回答

0

while($row = mysql_fetch_assoc($result)) {...}后,你已经达到了你的结果集的末尾。如果要再次读取结果集,必须将结果指针倒回到结果集的开头。通过使用

while($row = mysql_fetch_assoc($result)){ ... } 
mysql_data_seek($result, 0); // Rewind result pointer 
while($row = mysql_fetch_assoc($result)){ ... } 
mysql_data_seek($result, 0); // Rewind result pointer 
while($row = mysql_fetch_assoc($result)){ ... } 
+3

一般说明:不要使用mysql_ *函数。他们已经过时了。切换到mysqli_ *函数。 – maxhb

0

首先让你的结果和安全数组把它们做到这一点:

$table .= "</tr><tr class='tr'>"; 
foreach ($row as $r){ 
    $table .= " 
     <td class='td'>Minimum Bid: <b>"; 
     $table .= $r['MinBid']; 
     $table .= "</b></td>"; 
} 

while($r = mysql_fetch_assoc($result)){ 
    $row[] = $r; 
} 

然后尽可能经常需要建立这样的表重用阵列

...是的,mysql函数已被弃用。当你转移到PHP7时,他们将会消失。改用PDO或mysqli。