[英]PHP+MySQL Printing a MySQL array into table
我有一個查詢函數(下面的代碼),用於讀取數據庫,我想知道如何循環打印以將結果全部輸出到表中,如下所示:
我用它來得到它:
$visa=$DB->query("SELECT fname,lname,email FROM users");
echo '<table BORDERCOLOR=black>';
?>
<tr>
<th>Name</th><th>LastName</th><th>E-Mail</th>
</tr>
<?php
echo "<td>";
echo $visa[0]['fname'];
echo "</td>";
echo "<td>";
echo $visa[0]['lname'];
echo "</td>";
echo "<td>";
echo $visa[0]['email'];
echo "</td>";
查詢功能:
function query($querytext) {
$rs = mysql_query($querytext, $this->_link);
if($this->_debug) {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Query: (".@mysql_num_rows($rs).")</b></td>\n\t\t<td>" . htmlspecialchars($querytext) . "</td>\n\t</tr>\n");
if(mysql_error() != '') {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Error #".mysql_errno($this->_link)." :</b></td>\n\t\t<td>" . htmlspecialchars(mysql_error($this->_link)) . "</td>\n\t</tr>\n");
}
}
if($rs) {
$num_rows = @mysql_num_rows($rs);
if($num_rows) {
if($num_rows > 0) {
$rsarray = array();
while($line = mysql_fetch_array($rs , MYSQL_ASSOC)) {
array_push($rsarray, $line);
}
mysql_free_result($rs);
return $rsarray;
} else {
return false;
}
} else {
if(mysql_affected_rows($this->_link) > 0) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
用於for或foreach循環:
<?php foreach($visa as $v) {
echo "<td>";
echo $v['fname'];
echo "</td>";
echo "<td>";
echo $v['lname'];
echo "</td>";
echo "<td>";
echo $v['email'];
echo "</td>";
}
在您的代碼中, $visa
是查詢結果的數組,要顯示它的所有值,您只需在該數組上循環
您也可以遍歷字段名稱,如下所示:
<?php
// replace with your own array from the DB query
$visas = array(
array( 'name' => 'John',
'age' => '43'),
array( 'name' => 'Sally',
'age' => '36')
);
echo "Visas<br/><table border='1'>";
foreach($visas as $visa) {
echo "<tr>";
foreach($visa as $key => $value) {
echo "<td><em>$key:</em></td><td>$value</td>";
}
echo "</tr>";
}
echo "<table>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.