我有一个显示个人资料信息的页面,它由两个表格连接..
表1 - 用户
1 | email | bill
表2 - 图像
1 | 1 | image1.jpg
2 | 1 | image2.jpg
3 | 1 | image3.jpg
4 | 1 | image4.jpg
5 | 1 | image5.jpg
我有一切显示,我不确定是否能够实现多个图像列表。
如果用户ID在上传图片时为1,则还会插入1
的ID所以,如果用户有5张图片,我希望它显示为
<img src="images/gallery/$cover_img"></a>
<img src="images/gallery/$cover_img"></a>
<img src="images/gallery/$cover_img"></a>
<img src="images/gallery/$cover_img"></a>
<img src="images/gallery/$cover_img"></a>
但是现在它只会显示1张图片
$db = dbconnect();
$stmt = $db->prepare('SELECT * FROM `users` LEFT JOIN `images` ON images.id = users.id GROUP BY users.id');
$stmt->execute();
$result = $stmt->get_result();
答案 0 :(得分:0)
无需使用join和group by query,您也可以使用foreach循环来获取值。
<?php
try {
$sql1='select * from users' ;
foreach ($dbh->query($sql1) as $row)
{
$uid=$row['id'];
$sql2='select * from images where id='.$uid.'' ;
foreach ($dbh->query($sql2) as $row2)
{
$images=$row2['cover_image'];
}
}
$dbh = null;
} catch (Exception $ex) {
echo "Some Exception Occured " . $ex;
}
?>
答案 1 :(得分:0)
您应该像下面一样更新您的查询,以获取您想要的正确数据。
以下是获取数据的MySQL query
示例1:获取所有用户图片
SELECT
user.email,
user.bill,
images.id,
images.cover_image
FROM user
INNER JOIN images ON user.id=images.id
ORDER BY images.id ASC
示例2:获取单个用户图片
SELECT
user.email,
user.bill,
images.id,
images.cover_image
FROM user
INNER JOIN images ON user.id=images.id
WHERE user.id= 1 #Here 1 is the user ID
以下是使用
的示例mysqli
users
表
+----------+-----------------+----------+
| id | email | bill |
+----------+-----------------+----------+
| 1 | email@email.com | 5000 |
+----------+-----------------+----------+
images
表
+----------+-----------------+----------------+
| id | user_id | cover_image |
+----------+-----------------+----------------+
| 1 | 1 | image1.jpg |
+----------+-----------------+----------------+
| 2 | 1 | image2.jpg |
+----------+-----------------+----------------+
| ... | ... | ... |
+----------+-----------------+----------------+
PHP and MySQL
使用mysqli
#$db = dbconnect();
$db = new mysqli("HOSTNAME", "USER", "PASSWORD", "DATABASE_NAME");
if($db->connect_error){
die("$db->connect_errno: $db->connect_error");
}
$sql = '
SELECT
users.email,
users.bill,
images.user_id,
images.cover_image
FROM users
INNER JOIN images ON users.id=images.user_id
ORDER BY images.id ASC';
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
Display Images
来自$result
<?php while ($row = $result->fetch_array(MYSQLI_ASSOC)){ #Get every row as an Associative array?>
<img src="images/gallery/<?php echo $row['cover_image'] ?>" alt="<?php echo $row['cover_image'] ?>"></a>
<?php } ?>
答案 2 :(得分:-1)
要实现这一点,你需要用你的mysql查询替换LEFT JOIN和RIGHT JOIN。