使用用户ID上传后无法显示列表中的图像

时间:2019-03-01 11:27:40

标签: javascript php html

我试图在上传后在列表中显示图像,我希望php使用数据库中的'user_id'获取图像。

这是我的PHP代码

<div class="container-two">
    <?php
        $image = "";
        $caption = "";
        if ("POST" == $_SERVER['REQUEST_METHOD']){
            $caption = $_POST['Caption'];
            $con = mysqli_connect("localhost","root","Y1qSYlz1iTNBMCfY","schedios");
            $query = "SELECT Img_dir FROM images WHERE user_id = '".$_SESSION['user_id']."' ";
            $result = mysqli_query($con,$query);
            $row = $result->mysqli_fetch_assoc();
            $image = $row['Img_dir'];
        }


    ?>

<div>
    <?php
            $array = array();

            while ($row =   mysqli_fetch_assoc($query) ) {

            $array['user_id'] = $row['user_id'];
            echo "<ul><li ><img src='$image' ></li></ul>";}

    ?>
</div>

我有一个设计师表,所以这是仪表板,用户可以在其中上传图像并显示,谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

看来,您正在尝试仅以li回显图像目录,因此尝试在上传时将完整的图像路径保存在数据库中,让我给您提供示例代码以供参考。


  1. 接收用户从表单上传的图片:

           // image file directory
           $target = "images/".basename($image);
    
            $sql = "INSERT INTO images (user_id,image) 
                        VALUES 
                       ('".$_SESSION['user_id']."','$image')";
           // execute query
           mysqli_query($con, $sql);
    
          if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
            $msg = "Image uploaded successfully";
           }else{
            $msg = "Failed to upload image";
         }
      }
      $result = mysqli_query($db, "SELECT * FROM images WHERE user_id = 
               '".$_SESSION['user_id']."' ");
      ?>
    

2。在无序列表上向用户显示图像:

<div id="content">
  <?php
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
        echo "<ul><li>img src='images/".$row['image']."' /><li></ul>";
      echo "</div>";
    }
  ?>

答案 1 :(得分:0)

您为什么要获取$ query?

$row =   mysqli_fetch_assoc($query)

如果我说对了,您应该对$ result做同样的事情

 while ($row =   mysqli_fetch_assoc($query) ) {
        $image = $row['Img_dir']; // maybe add $row['Img_name'] if exist in your database
       // $array['user_id'] = $row['user_id'];// you already know userid from $_SESSION, right ?
        echo "<ul><li ><img src='$image' ></li></ul>";}