2016-12-09 79 views
1

我有這樣一個數據庫,並希望獲取的圖像到我的網站就是這樣,見截圖PHP MySQL - 如何獲取像這樣?

enter image description here

,但我不知道,沒有SQL能賣到這樣的嗎?我知道只有

$sql = "SELECT id, photographer, image FROM MyTable"; 
$result = mysqli_query($conn, $sql); 

while($row = mysqli_fetch_assoc($result)) 
       { 
        echo "<tr>"; 
        echo "<td align='center'>".$i."</td>"; 
        echo "<td>".$row['photographer']."</td>"; 
        echo "<td><img src='".$row['image']."'></td>"; 

        echo "</tr>"; 

       } 

但它不顯示我想要的。我應該怎麼做?或者我設計數據庫錯了?

+0

你爲什麼迴應'username','password'和'email'?這些不是您選擇的列。 – Barmar

+0

請參閱http://stackoverflow.com/questions/27575562/how-can-i-list-has-same-id-data-with-while-loop-in-php/27575685#27575685瞭解如何保持相關行在表中一起輸出。它演示瞭如何使用每個組的標題行執行此操作,但是可以使用相同的總體思路將所有圖像放在表格的同一行中。 – Barmar

+0

@Barmar就是這樣。 – doflamingo

回答

1

數據庫設計並非全部錯誤。您可以創建另一張表來存儲不同的攝影師,並將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

相關問題