0

I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.

Here is my code that has to display the images.

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

Connection to database

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

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

?>

And here is the database connection from the html form.

<?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();
    }
}
?>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    Ok, so using the browsers debugger (F12) Check the `Network` tab. Now does it say that the images are being downloaded or that they are failing with an error – RiggsFolly Dec 17 '21 at 15:28
  • ___Pointer___ Doing a `SELECT * FROM photos` just to then do a `mysqli_num_rows($result);` is a really inefficient way of getting a count of rows in a table. Intead do a `SELECT COUNT(columnName) as numRows FROM photos` One day you may have amillion photos in that table – RiggsFolly Dec 17 '21 at 15:31
  • Also if you are just going to Add One to the row count to decide the sort order, add an `id` column to the table and set it to Auto Increment and then you can let MySQL build the sort order automatically and MUCH QUICKER – RiggsFolly Dec 17 '21 at 15:33
  • It seems that you are saving the uploaded image in a folder above the script or document root. So is this folder accessible through the HTTP server? Perhaps try putting them into a `img` folder at the root of your site and see if things change or not. Do files get uploaded correctly? – Patrick Janser Dec 17 '21 at 15:35
  • @RiggsFolly it shows an error - 404 (Not Found) – Fred SEBOWA Dec 17 '21 at 15:40
  • Ok, so what is your directory structure like on the server. Where do those 2 scripts live in your directory structure – RiggsFolly Dec 17 '21 at 15:43
  • 1
    Don't forget to filter the data you print in your HTML. You should replace `$row["filetitle"]` by `htmlspecialchars($row['filetitle'])`. Another point: Normally an inline type of tag such as `` should not contain a block type of tag (in your case ` – Patrick Janser Dec 17 '21 at 15:45
  • @PatrickJanser, when I upload the files, I can see them in the destination folder, however, I can't see them on the website. – Fred SEBOWA Dec 17 '21 at 15:45
  • 1
    So check what @RiggsFolly says and what I pointed out about the directory structure. You are serving images from a parent folder so you have to be sure it is accessible over HTTP. – Patrick Janser Dec 17 '21 at 15:46
  • @RiggsFolly, the 2 scripts live in the website folder; so they are both in the same directory. – Fred SEBOWA Dec 17 '21 at 15:59
  • So this `"../libraries/photos/"` means the photo's are in a directory above the DocumentRoot, and therefore cannot be served by the web server. See @PatrickJanser comment about moving that folder into a directory under the DocumentRoot – RiggsFolly Dec 17 '21 at 16:02
  • Should I put everything in one directory? Because right now I have a folder that has the scripts and another separate folder containing the uploaded images. Both folders are under one parent folder. – Fred SEBOWA Dec 17 '21 at 16:04
  • Try a folder under the DocRoot like `libraries/photos/` without the `../` and create those 2 folders under the doc root – RiggsFolly Dec 17 '21 at 16:07
  • @RiggsFolly, I tried it but still showing me same output (the title and description without the photo) – Fred SEBOWA Dec 17 '21 at 16:16
  • 1
    Did you cahnge the code to get the images from the new location – RiggsFolly Dec 17 '21 at 16:26
  • What **exactly** is not working? What have you tried to resolve the problem? If an error 404 is thrown, maybe the URL is not the correct one? – Nico Haase Dec 17 '21 at 20:55
  • @NicoHaase, the images aren't displayed in my website, I can only see the Name and description of the images – Fred SEBOWA Dec 28 '21 at 10:20
  • Please add all clarification to your question by editing it. Did you check whether you are using the proper URL to the images? – Nico Haase Dec 28 '21 at 13:31
  • The code is now working; the issue was with the database format in which the filenames were stored. Thank you all for your help. – Fred SEBOWA Jan 13 '22 at 21:47

1 Answers1

-1

For example, if you use this code, you can load an image from 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'].'">';
    }
    ?>
Asad Shiekh
  • 31
  • 12
  • Be careful not to implement an injection vulnerability when concatenating values ​​to a string to be interpreted. In this case you should make sure that the value of `$id1` contains no single quote. See [this answer](https://stackoverflow.com/q/332365/2158271) for more information. – haba713 Dec 17 '21 at 20:37
  • Please add some explanation to your answer such that others can learn from it. `mysql_*` was removed from PHP years ago – Nico Haase Dec 17 '21 at 20:54