我有一个由多个表组成的JOIN。
$sql_entries = "SELECT transaction_information . *, customer_information . * , property_information . *, borrowers . *, lenders . *, listing_agents . *, payoff . *, sellers . *, selling_agents .*
FROM transaction_information
JOIN customer_information ON transaction_information.entry_no = customer_information.entry_no
JOIN property_information ON transaction_information.entry_no = property_information.entry_no
JOIN borrowers ON transaction_information.entry_no = borrowers.entry_no
JOIN lenders ON transaction_information.entry_no = lenders.entry_no
JOIN listing_agents ON transaction_information.entry_no = listing_agents.entry_no
JOIN payoff ON transaction_information.entry_no = payoff.entry_no
JOIN sellers ON transaction_information.entry_no = sellers.entry_no
JOIN selling_agents ON transaction_information.entry_no = selling_agents.entry_no
";
它返回大约50+列。我想在上面显示列名,在下面显示值。
我试图使用以下代码,但它没有给我想要的结果。
$result_entries = $conn->query($sql_entries);
if ($result_entries->num_rows > 0) {
echo '<div id="total"><table class="table table-striped table-bordered table-responsive">';
echo "<tr>";
//$entries = array();
while($row = $result_entries->fetch_assoc()) {
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr>';
}
//ROw of Table heading ends.
// Fetch values in the columns under the respective heads.
while($row1 = $result_entries->fetch_assoc()) {
echo '<tr>';
foreach ($row1 as $col) {
echo '<td>'.$col.'</td>';
//This wil return Object and I know. But I don't want to use $row['indexName'] and repeat myself for fetching values as there are too many columns.
}
echo '</tr>';
}
echo "</table></div>";
} else {
echo "0 results for Entries";
}
好的,我的第一个问题是迭代每一行的值,而不做像$row['indexname']这样的事情其次,我的列标题在同一行中也重复了两次。
使用array_keys()
可以获得列名。然后使用implode()
,你可以建立你的标题行,与<th></th>
。要在第一个循环中只回显标题行,可以使用布尔变量,即。$header = true;
。然后在回显标题行后将其设置为false,它将不再输出。你的代码看起来像-
$result_entries = $conn->query($sql_entries);
if ($result_entries->num_rows > 0) {
echo '<div id="total"><table class="table table-striped table-bordered table-responsive">';
$headers = true;
while($row = $result_entries->fetch_assoc()) {
// echo headers on 1st iteration
if($headers){
echo "<tr><th>".implode("</th><th>",array_keys($row))."</th><tr>";
$headers = false;
}
// echo row values
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>".$value."</td>";
}
echo "</tr>";
}
echo "</table></div>";
} else {
echo "0 results for Entries";
}