【问题标题】:echo multiple images from one array in PHP/HTML在 PHP/HTML 中从一个数组中回显多个图像
【发布时间】:2016-06-18 22:30:48
【问题描述】:

这个页面应该从 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  
   }
?>

【问题讨论】:

    标签: mysql arrays fetch


    【解决方案1】:

    首先,您的查询应该是这样的:

    $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.
    

    然后,您需要在您的while 中使用$images = explode(',', $row_post['img']); 来生成图像数组。

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

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

    【讨论】:

      猜你喜欢
      • 2015-11-06
      • 2011-06-10
      • 2017-01-10
      • 2013-10-23
      • 2013-11-02
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多