數據庫設計並非全部錯誤。您可以創建另一張表來存儲不同的攝影師,並將MyTable
表的photographer
列作爲外鍵。
photographer_tb:
id | photographer_name
---+--------------------
1 | Photographer A
2 | Photographer B
3 | Photographer C
MyTable的:
id | photographer_id | image
---+-----------------+-----------
1 | 1 | foo1.jpg
2 | 1 | foo2.jpg
3 | 1 | foo3.jpg
4 | 2 | foo4.jpg
5 | 2 | foo5.jpg
6 | 3 | foo6.jpg
然後,你可以實現顯示器要兩個選項:
首先是JOIN
(?)查詢:
$sql = "SELECT * FROM MyTable a LEFT JOIN photographer_tb b ON a.id = b.photographer_id";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
if(empty($lastphotographer)){
echo '<tr>
<td align="center">'.$row['photographer_name'].'</td>
<td>';
} else if($lastphotographer != $row['photographer_name']){
echo '</td></tr>
<tr>
<td>'.$row['photographer_name'].'</td>
<td>';
}
echo '<img src="'.$row['image'].'">';
$lastphotographer = $row['photographer_name'];
}
echo (mysqli_num_rows($result) > 0)?'</td></tr>':'';
第二個是一個嵌套循環。循環首先攝影師,那裏面的所有鏈接的圖像的運行另一個循環:
$sql = "SELECT id, photographer_name FROM photographer_tb";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
echo '<tr>
<td align="center">'.$row['photographer_name'].'</td>
<td>';
$sql2 = "SELECT images FROM MyTable WHERE photographer_id = '$row[id]'";
$result2 = mysqli_query($conn, $sql);
while($row2 = mysqli_fetch_array($result2)){
echo '<img src="'.$row2['images'].'">';
}
echo '</td></tr>';
}
您也可以參考您的文章的其他可行方案的意見。當您使用mysqli_*
時,請檢查prepared statement。
你爲什麼迴應'username','password'和'email'?這些不是您選擇的列。 – Barmar
請參閱http://stackoverflow.com/questions/27575562/how-can-i-list-has-same-id-data-with-while-loop-in-php/27575685#27575685瞭解如何保持相關行在表中一起輸出。它演示瞭如何使用每個組的標題行執行此操作,但是可以使用相同的總體思路將所有圖像放在表格的同一行中。 – Barmar
@Barmar就是這樣。 – doflamingo