我有一个这样的数据库,想把这样的图片传到我的网站上,请看截图
但我不知道,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>";
}
但这并不是我想要的。我该怎么办?或者我设计的数据库错了?
最佳答案
数据库设计并非完全错误。您可以创建另一个表来存储不同的摄影师,并将表的photographer
列作为外键。
摄影师:
id | photographer_name
---+--------------------
1 | Photographer A
2 | Photographer B
3 | Photographer C
我的表:
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
那么,你可以有两个(?)实现所需显示的选项:
首先是一个
MyTable
查询:$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>';
}
你也可以参考你文章的评论来寻找其他可行的选择。当您已经在使用
JOIN
时,请选中prepared statement。关于php - PHP MySQL-如何获取这样的内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41052288/