[英]Php sql Left Join Tables Echo columns from table 1
I have two tables blog and tbl_users. 我有两个表blog和tbl_users。 blog contains columns 'blogid','message','title','name','created' & 'image_ctgy'.
Blog包含“ blogid”,“ message”,“ title”,“ name”,“ created”和“ image_ctgy”列。 tbl_users contains columns 'userPic', 'image_ctgy', 'userId'.
tbl_users包含“ userPic”,“ image_ctgy”,“ userId”列。 The code below displays the blog message and the associated images with that blog messsage based on the same image_ctgy.
下面的代码基于相同的image_ctgy显示博客消息和具有该博客消息的关联图像。 However my knowledge of php is limited and I am having difficulty in displaying the title, name & created columns along with the blog message.
但是,我对php的了解有限,并且在显示标题,名称和创建的列以及博客消息时遇到困难。 Any help would be appreciated.
任何帮助,将不胜感激。
$sql = "SELECT blog.message as blogmessage, tbl_users.userPic as tblPics
FROM blog
LEFT JOIN tbl_users ON(blog.image_ctgy = tbl_users.image_ctgy)
ORDER by blog.blogid DESC";
$stmt = $db->prepare($sql);
$stmt->execute();
$blogs = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$blogmessage = $row['blogmessage'];
$blogs[$blogmessage] [] = $row['tblPics'];
}
?>
<html>
<body>
<?php
foreach ($blogs as $blogmessage => $tblPics)
{
?>
<h2><?php echo $blogmessage; ?></h2>
<ul>
<?php
foreach ($tblPics as $tblPic)
{
?>
<li> <img src="cms3/user_images/<?php echo $tblPic; ?>"width="50px" height="50px"/></li>
<?php
}
?>
</ul>
<?php
}
?>
</body>
</html>
You can use this code to get fields title, name, created along with message and userPic: 您可以使用以下代码获取字段标题,名称以及消息和userPic创建的字段:
<?php
$sql = "SELECT blog.message as blogmessage, blog.title, blog.name, blog.created, tbl_users.userPic as tblPics
FROM blog
LEFT JOIN tbl_users ON(blog.image_ctgy = tbl_users.image_ctgy)
ORDER by blog.blogid DESC";
$stmt = $db->prepare($sql);
$stmt->execute();
$blogs = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
// here you can get along with blogmessage another desired columns:
// title, name, created
$blogmessage = $row['blogmessage'];
$blogs[$blogmessage] [] = $row['tblPics'];
}
?>
<html>
<body>
<?php
foreach ($blogs as $blogmessage => $tblPics)
{
?>
<h2><?php echo $blogmessage; ?></h2>
<ul>
<?php
foreach ($tblPics as $tblPic)
{
?>
<li> <img src="cms3/user_images/<?php echo $tblPic; ?>"width="50px" height="50px"/></li>
<?php
}
?>
</ul>
<?php
}
?>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.