2016-03-05 105 views
0

此頁面應該回復帖子表中的帖子,並將它們與圖像表中具有相同post_id的圖像進行鏈接。每篇文章可以包含多個圖像或根本不包含圖像。我希望能夠回顯鏈接到特定帖子的所有圖像。從PHP/HTML中的一個數組中回顯多個圖像

<?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 
    } 
?> 

回答

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"/>'; 
    } 
} 
相關問題