在PHP / HTML中回显来自一个数组的多个图像

时间:2016-03-05 01:06:44

标签: mysql arrays fetch

此页面应该回显post表中的帖子,并将它们与images表中具有相同post_id的图像链接起来。每个帖子可以包含多个图像或根本没有图像。我希望能够回显链接到特定帖子的所有图像。

<?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);                   
    include("db.php");
    $select_post = "select * from post as p
                    union 
                    select img from images as i
                    on i.post_id = p.post_id";

    $run_post = mysqli_query($conn, $select_post);

    while ($row_post=mysqli_fetch_array($run_post)){
        $post_id =  $row_post['post_id'];
        $post_title =   $row_post['post_title'];
        $post_date =    $row_post['post_date'];
        $post_author =  $row_post['post_author'];
        $post_content = substr($row_post['post_content'],0,100);        
        $post_image =   $row_post['img'];
        $post_image .=  '<img src="post_image/'.$post_image.'" width="60" height="60"/>';
        ?>
        <tr align="center">
            <td><?php echo $post_id; ?> </td>
            <td><?php echo $post_date; ?></td>
            <td><?php echo $post_author; ?></td>
            <td><?php echo $post_title; ?></td>

            <td><?php echo $post_image; ?></td>
            <td><?php echo $post_content; ?></td>
            <td><center><button><a href="delete.php?del=<?php echo $post_id;?>" style="text-decoration:none; color:red; font-weight:bold;">X</a></button></center></td>
            <td><center><button><a href="edit.php?edit=<?php echo $post_id;?>" style="text-decoration:none; color:red; font-weight:bold;"">Edit</a></button></center></td>
        </tr>
        <?php  
   }
?>

1 个答案:

答案 0 :(得分:0)

首先,您的查询应该是:

$select_post = "SELECT p.*, i.img 
                FROM post p
                LEFT JOIN (
                    SELECT 
                        group_concat(img) as img, 
                        post_id
                    FROM images
                    GROUP BY post_id
                ) i ON i.post_id = p.post_id";
// this query can be optimized a bit i think, but it should do the job.

然后,您需要在$images = explode(',', $row_post['img']);while生成一系列图片。

循环$images并根据需要处理它们。

$post_image = '';
if(count($images) > 0){
    foreach($images as $image){
         $post_image .= '<img src="post_image/'.$image.'" width="60" height="60"/>';
    }
}