【问题标题】:Displaying images from Database not working显示数据库中的图像不起作用
【发布时间】:2022-01-20 12:03:39
【问题描述】:

我尝试了多种方法,但我的代码仍然没有显示我网站上数据库中的图像。当我点击上传时,我只得到文件名和文件详细信息的输出,但没有显示照片。

这是我必须显示图像的代码。

 <main>
     <section align='center'>
     <h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
     <br><br>
         <div class="wrapper">
             <!--h2 align='left'>Photos</h2-->

          <div class="photo-container"> 

<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "Error updating photo library!";
}else{
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
            
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<a href="#">
                  <div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
                  <h3>'.$row["filetitle"].'</h3>
                  <p>'.$row["filedescription"].'</p>
               </a>';
    }
}
?>
          </div>
         </div>
     </section>
 </main>

连接数据库

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";

$conn = mysqli_connect($servername, $username, $password, $dbname);

?>

这是来自 html 表单的数据库连接。

<?php


if(isset($_POST['upload'])) {
    $newFileName = $_POST['filename'];
    if(empty($newFileName)){
        $newFileName = "photo";
    }else{  
        //Replacing spaces in filename with underscores
        $newFileName = strtolower(str_replace(" ", "-", $newFileName));
    }
    $filetitle = $_POST['filetitle'];
    $filedescription = $_POST['filedescription'];
    
    $file = $_FILES['file']; 

    $fileName = $file["name"];
    $fileType = $file["type"];
    $fileTempName = $file["tmp_name"];
    $fileError = $file["error"];
    $fileSize = $file["size"];

    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array("jpg", "jpeg", "png");

    //Error handling for allowed file types
    if(in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if($fileSize < 10000000) {
                //Make file unique through naming
                $imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
                $fileDestination = "../libraries/photos/" . $imageFullName;

                include_once "dbh.php";

                //Checking for error handling when fields have been left empty
                if(empty($filetitle) || empty($filedescription)) {
                    header("location:photos_edit.php?upload=empty");
                    exit();
                } else {
                    $sql = "SELECT * FROM photos;";
                    $stmt = mysqli_stmt_init($conn); 
                    if (!mysqli_stmt_prepare($stmt, $sql)) {
                        echo "SQL statement failed!";
                    }else{
                        mysqli_stmt_execute($stmt);
                        $result = mysqli_stmt_get_result($stmt);
                        $rowCount = mysqli_num_rows($result);
                        $setPhotoOrder = $rowCount + 1;

                        $sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
                        if (!mysqli_stmt_prepare($stmt, $sql)) {
                            echo "SQL statement failed!";
                        }else{
                            mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
                            mysqli_stmt_execute($stmt);

                            move_uploaded_file($fileTempName, $fileDestination);
                            header("location: photos_edit.php?upload=success");
                        }
                    }
                }
            }else{
                echo "Photo is too big!";
                exit();
            }
        }else{
            echo "An error ocurred while uploading your image!";
            exit();
        }
    }else{
        echo "File type not supported";
        exit();
    }
}
?>

【问题讨论】:

  • 好的,所以使用浏览器调试器 (F12) 检查Network 选项卡。现在它是说正在下载图像还是因为错误而失败
  • Pointer 执行SELECT * FROM photos 然后执行mysqli_num_rows($result); 是获取表中行数的一种非常低效的方法. Intead 做一个SELECT COUNT(columnName) as numRows FROM photos 有一天你可能在那张桌子上有一百万张照片
  • 不要忘记过滤您在 HTML 中打印的数据。您应该将$row["filetitle"] 替换为htmlspecialchars($row['filetitle'])。另一点:通常,内联类型的标签,如&lt;a&gt; 不应包含块类型的标签(在您的情况下为&lt;div&gt;)。但是您可以将&lt;img&gt; 标签放在&lt;a&gt; 标签内,因为图像是内联块。
  • 所以请检查@RiggsFolly 所说的以及我指出的有关目录结构的内容。您正在从父文件夹提供图像,因此您必须确保可以通过 HTTP 访问它。
  • 您是否更改了从新位置获取图像的代码

标签: php html sql


【解决方案1】:

例如,如果您使用此代码,则可以从 DB (MySQL) 加载图像:)

<?php
       $connection =mysql_connect("localhost", "root" , "");
       $sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
      $imageresult1 = mysql_query($sqlimage,$connection);

      while($rows = mysql_fetch_assoc($imageresult1))
    {       
       echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
    }
    ?>

【讨论】:

  • 在将值连接到要解释的字符串时注意不要实现注入漏洞。在这种情况下,您应该确保 $id1 的值不包含单引号。请参阅this answer 了解更多信息。
  • 请在您的答案中添加一些解释,以便其他人可以从中学习。 mysql_* 多年前已从 PHP 中删除
猜你喜欢
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多