我試圖從我的主表(父母詳細信息)中顯示一行數據,然後在這些行的每一行下顯示另一個表中的子女姓名。我不得不使用下面的代碼一展身手:運行到使用PHP選擇和分組結果
$sql="select distinct members_main.first_name as main_firstname,
members_main.first_name as main_firstname,
members_main.last_name as main_lastname,
members_main.address_1 as main_address_1,
members_main.address_2 as main_address_2,
members_main.address_3 as main_address_3,
members_main.address_4 as main_address_4,
members_main.post_code as main_post_code,
members_main.home_tel as main_home_tel,
members_main.mobile as main_mobile,
members_main.home_email as main_home_email
from members_main, members_family where members_main.contact_id=members_family.contact_id";
$sql2="select members_family.first_name as fam_firstname,
members_family.last_name as fam_lastname
from members_family, members_main
where members_main.contact_id=members_family.contact_id";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
echo '<table width="100%" cellpadding="3" cellspacing="0">
<tr>
<th align="left" valign="top">First Name</th>
<th align="left" valign="top">Last Name</th>
<th align="left" valign="top">Address 1</th>
<th align="left" valign="top">Address 2</th>
<th align="left" valign="top">Address 3</th>
<th align="left" valign="top">Address 4</th>
<th align="left" valign="top">Post Code</th>
<th align="left" valign="top">Home Tel</th>
<th align="left" valign="top">Mobile</th>
<th align="left" valign="top">Email</th>
</tr>';
echo '<tr>
<td valign="top">'.$rows['main_firstname'].'</td>
<td valign="top">'.$rows['main_lastname'].'</td>
<td valign="top">'.$rows['main_address_1'].'</td>
<td valign="top">'.$rows['main_address_2'].'</td>
<td valign="top">'.$rows['main_address_3'].'</td>
<td valign="top">'.$rows['main_address_4'].'</td>
<td valign="top">'.$rows['main_post_code'].'</td>
<td valign="top">'.$rows['main_home_tel'].'</td>
<td valign="top">'.$rows['main_mobile'].'</td>
<td valign="top">'.$rows['main_home_email'].'</td>
</tr>';
$result2=mysql_query($sql2);
echo '<table width="100%" cellpadding="3" cellspacing="0">
<tr>
<th align="left" valign="top">First Name</th>
<th align="left" valign="top">Last Name</th>
</tr>';
while($rows=mysql_fetch_array($result2)){
echo '<tr>
<td valign="top">'.$rows['fam_firstname'].'</td>
<td valign="top">'.$rows['fam_lastname'].'</td>
</tr>';
}
}
echo "</table>";
我得到的所有行從表members_family每每條記錄從members_main。 members_family中可以有多個記錄,這些記錄將與members_main中的一條記錄相關聯。基本上,members_main(parent)可以在members_main中擁有多個子項。
您$ SQL2必須是您的主,而(){}內,它會從你也先需要輸入選擇只有孩子,該父 – Dave 2013-05-13 11:52:27
感謝戴夫。我怎麼做?我是一個PHP新手! – user2281899 2013-05-13 11:53:43
'$ sql2 =「select members_family.first_name as fam_firstname, members_family.last_name as fam_lastname from members_family where contact_id =」。$ rows ['contact_id'];'這樣的東西就在'$ result2 ='位之上,您需要確保將主要SQL查詢中的contact_id拉出。 – Dave 2013-05-13 11:55:22