![](/img/trans.png)
[英]Efficient way to calculate number of foreign keys in second table and display it with rows from first table - PHP - MySQL
[英]Display MySQL table ( number of rows are not same ) in PHP
我有一個 MySQL 表,它有兩列 -
我想像這樣在我的網站上顯示 -
我可以輕松取表名Boy | Girl
Boy | Girl
。 但是當我嘗試顯示表格時,我得到了這樣的 -
我只是在這里展示一個例子。 可能有 50 個男孩和 10 個女孩。所以我需要幫助。
顯示標題后
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
這么多觀點,但沒有得到任何答案。 請幫助伙計們。 請抓住我的錯誤。
嘗試使用兩個查詢。 為每個類別(男性和女性)制作一個數組它有效。
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".@$males[$i]."</td><td>".@$females[$i]."</td></tr>";
}
試試這個查詢 100% 工作但設置 php 代碼。
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM (SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
您的問題與使用 PHP 創建表有關還是與 SQL 查詢本身有關?
如果是表的創建,那么我建議您像這樣使用嵌入在單個表中的兩個表。 這樣,您可以使用一個 SQL 查詢構建第一個表,然后使用第二個查詢構建第二個表,然后顯示該表,無論每邊有多少條目,女孩和男孩都會並排出現。 你的代碼看起來有點像這樣:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
如果您需要滿足更多類別,請進行初始搜索以確定不同的類別,然后將上面創建內表的代碼部分放入循環中。
例如。 在偽代碼中:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.