繁体   English   中英

如何从数据库中获取所有图像

[英]how to fetch all the images from the database

我有一个数据库表,在其中存储了图像名称和StudentId。 我正在使用studentId从当前学生那里获取图像,就像Instagram主页一样,您可以在其中查看所有上传的图像。 我不是将图像存储到数据库中,而是将所有图像保存到名为“ upload /”的目录中,并且只有图像名称被保存到数据库中。

我的数据库中目前有3张图片,带有相同的StudentId。 但是问题是有时我只能获取一个图像,也不能获取任何图像。 我已经尝试了许多代码,但是仍然无法正常工作。 我不确定错误在哪里。 是在循环还是我无法从数据库中获取所有图像。

<?php
session_start();
include 'common.php';
$id = $_SESSION['student'];
$command = "SELECT * FROM UsersImages WHERE StudentId = ".$id;
$stmt = $dbh->prepare($command);
$result = $stmt->execute();
?>
<html>
   <head>
      <meta charset="UTF-8">
      <title>hello</title>
   </head>
<body>
   <nav>
      <ul>
         <li><a href="home.php">Home</a></li>
         <li><a href="profile.php">Upload</a></li>
      </ul>
   </nav>
   <div>
     <?php
     $row = $stmt->fetch();
     $dir = $row['img_name'];
     foreach($dir as $images){
     echo "<img src=". $images." alt='images'>";
     }
     ?>
   </div>
</body>
</html>

只是更新您的php代码,您只存储错误处理的图像名称,因此它将不起作用,并使用fetch_assoc()处理您的数组数据

<?php
     $row = $stmt->fetch();
     $dir = $row['img_name']; // this is wrong process
     foreach($dir as $images){
     echo "<img src=". $images." alt='images'>";
     }
     ?>

<?php
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); // get all result using this
foreach ($results as $data)
{
    $images = $data['img_name']; // get image then use it in your code
    echo "<img src=". $images." alt='images'>";
}
?>

尝试这个

$results = $stmt->fetch(PDO::FETCH_ASSOC); // get all result using this
    $images = $results['img_name']; // get image then use it in your code
    echo "<img src=". $images." alt='images'>";

有关使用循环选择数据的更多信息

https://www.w3schools.com/php/php_mysql_select.asp

请找到完整的答案。

  • 在获取数据时添加PDO :: FETCH_ASSOC
<?php
session_start();
include 'common.php';
$id = $_SESSION['student'];
$command = "SELECT * FROM UsersImages WHERE StudentId = ".$id;
$stmt = $dbh->prepare($command);
$result = $stmt->execute();
?>
<html>
   <head>
      <meta charset="UTF-8">
      <title>hello</title>
   </head>
<body>
   <nav>
      <ul>
         <li><a href="home.php">Home</a></li>
         <li><a href="profile.php">Upload</a></li>
      </ul>
   </nav>
   <div>
     <?php
     $images = $stmt->fetchAll(PDO::FETCH_ASSOC);
     foreach($images as $image){
     echo "<img src=". $image['img_name']." alt='images'>";
     }
     ?>
   </div>
</body>
</html>

希望这可以帮助 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM