I am trying to save 2 photos to my MySQL database. I can only see one of the 2 photos in the database (i.e. its name) but I see the 2 photos in the folder I store my photos. ( A picture of how the database looks like is attached.) When I try to display the 2 photos, I only see that one photo that I saw in the database. What is the problem here?

Html Code to upload photo

<input type="file" id="_photo"  name="_photo[]" multiple="multiple">
<input type="button" id="add_more" class="" value="Add More Files"/>

Code to save photos in database and folder

for ($i = 0; $i < count($_FILES["_photo"]["name"]); $i++) {  
    if (!empty($_FILES['_photo']['name'][$i])) {   
        if ($_FILES['_photo']['type'][$i] == 'image/jpeg') {
            $upload_folder = "./profile_pix/";
            $pic_name = time() . ".jpg";
            $pic_path = $upload_folder . $pic_name;
            require_once "include/resize.php";
                if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $pic_path)) {
                    $image = new Resize($pic_path);
                    $image->resizeImage(180, 180, 'crop');
                    $image->saveImage($pic_path);
                    //thumbnail
                    $image = new Resize($pic_path);
                    $image->resizeImage(50, 50, 'crop');
                    $image->saveImage($upload_folder . "thumb/" . $pic_name);
                }
            }   
    } 
    else {          
            $pic_name="default_house.png";          
    }
} 

Code to display Uploaded Photos

$sql = "SELECT * FROM myDatabase";
foreach ($db->query($sql) AS $result){
      echo "
       <img src='profile_pix/{$result['photos']}' width = '30' height ='30px' style=' margin-top:8px;'/>
       ";
 }

Dani AI

Generated

Short summary and likely causes: as and suggested, the most common mistake is inserting the filename into the database only once (or outside the loop), so only the last name ends up stored. Other runs-of-the-mill problems to check for are duplicate filenames (using time() can easily produce the same name and overwrite files), missing form enctype="multipart/form-data", upload limits in php.ini (post_max_size, upload_max_filesize, max_file_uploads), or a schema that only ever keeps one filename per user.

Concrete fixes and a modern pattern

  • Move the INSERT into the same loop that handles each uploaded file.
  • Generate truly unique filenames (preserve the original extension).
  • Use prepared statements (PDO or mysqli) and check for errors after each insert.
  • Store one photo per DB row (recommended) instead of stuffing multiple names into one column.

Example (focus: unique name + DB insert; resize step left where you already have it):

// prepare once
$stmt = $pdo->prepare("INSERT INTO photos (user_id, filename, created_at) VALUES (:uid, :fn, NOW())");

foreach ($_FILES['_photo']['name'] as $i => $origName) {
    if (empty($origName) || $_FILES['_photo']['error'][$i] !== UPLOAD_ERR_OK) continue;

    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    $filename = uniqid('img_', true) . '.' . $ext;
    $target   = __DIR__ . "/profile_pix/{$filename}";

    if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $target)) {
        // run your resize/save-thumbs code here (check for success)
        $stmt->execute([':uid' => $userId, ':fn' => $filename]);
        if ($stmt->rowCount() === 0) error_log("DB insert failed for $filename");
    } else {
        error_log("Failed to move uploaded file: $origName");
    }
}

Schema suggestion (one row per image)

CREATE TABLE photos (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  filename VARCHAR(255) NOT NULL,
  is_primary TINYINT(1) DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Quick debugging checklist

  • Inspect var_dump($_FILES) to verify the array contents.
  • Log each generated filename and whether the move/upload succeeded.
  • Check DB errors (use exceptions or errorInfo).
  • Verify upload folders (profile_pix and profile_pix/thumb) exist and are writable.
  • Confirm your SELECT uses the correct column name (e.g., filename) and that you iterate all rows.

Applying these changes (insert inside the loop, unique names, and proper error checks) will solve the “only one name in DB” symptom in almost every case.

Recommended Answers

All 2 Replies

The problem might be occuring at the time of saving pictures in the database (there are two photos in the folder but only one in the database). Post the code for saving the data into the database (I have a feeling that the insert query should be within the for loop).

As like broj1 mentioned the problem might be occuring at the time of saving pictures in the database. So the insert query should be within the for loop.
here is an example.

<?php
for ($i = 0; $i < count($_FILES["_photo"]["name"]); $i++) {  
    if (!empty($_FILES['_photo']['name'][$i])) {   
        if ($_FILES['_photo']['type'][$i] == 'image/jpeg') {
            $upload_folder = "./profile_pix/";
            $pic_name = time() . ".jpg";
            $pic_path = $upload_folder . $pic_name;
            require_once "include/resize.php";
                if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $pic_path)) {
                    $image = new Resize($pic_path);
                    $image->resizeImage(180, 180, 'crop');
                    $image->saveImage($pic_path);
                    //thumbnail
                    $image = new Resize($pic_path);
                    $image->resizeImage(50, 50, 'crop');
                    $image->saveImage($upload_folder . "thumb/" . $pic_name);
                }
            }   
    } 
    else {          
            $pic_name="default_house.png";          
    }

    //insert query
    $insert=mysql_query("INSERT INTO table_name(field1) VALUES('$pic_name')");

} ?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.