How to store file name in database, with other info while uploading image to server using PHP?

How to store file name in database, with other info while uploading image to server using PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Merging File Uploads with Database Records in PHP

Building a CMS to store band member profiles requires more than just moving files from a browser to a server directory. The core challenge lies in synchronizing two distinct actions: physically saving the image file and persisting its metadata—specifically the filename—into your database simultaneously. Relying on tutorials that treat these as separate tasks often leads to the exact frustration you are facing, where images appear on the disk but the database contains NULL or incorrect values.

The fundamental mechanism here is the $_FILES superglobal. When a form with enctype="multipart/form-data" is submitted, PHP populates this array with details about the uploaded resource. The most critical attribute for your use case is $_FILES['filep']['name']. This contains the original filename sent by the client. While it might be tempting to store this raw name, a robust implementation usually involves generating a unique identifier to prevent collisions and security issues later on.

Your current table schema defines the photo column as a varchar(30). This is perfectly suited for storing a filename string, but it implies that you are not storing the binary file data (BLOBs) directly in the database. Instead, your images/ directory must be writable, and the application logic must handle the physical move operation before attempting to write the record.

Handling the Upload Logic

The snippet you found uses move_uploaded_file() correctly to shift the temporary upload file to your permanent storage location. However, the subsequent database interaction contains a critical flaw: it attempts to insert the filename into the database without first validating that the upload actually succeeded or checking if the target directory is writable. Furthermore, the example code relies on deprecated mysql_* functions, which have been removed in modern PHP versions. You must migrate this logic to use PDO or MySQLi for security and compatibility.

Here is a refined approach using PDO that integrates the file move with the database insertion:

<?php
// Configuration
$uploadDir = 'images/';
$dbUser = 'root'; // Replace with your credentials
$dbPass = 'password'; // Replace with your credentials
$dbName = 'project';

// Initialize Database Connection using PDO
try {
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName", $dbUser, $dbPass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['filep'])) {
        $nameMember = $_POST['nameMember'];
        $bandMember = $_POST['bandMember'];
        $aboutMember = $_POST['aboutMember'];
        $otherBands = $_POST['otherBands'];

        // Validate file size and type if necessary
        $maxSize = 10 * 1024 * 1024; // 10MB limit
        
        if ($_FILES['filep']['size'] > $maxSize) {
            throw new Exception("File is too large.");
        }

        // Define the unique filename. Using a timestamp or random string prevents overwrites.
        // Alternatively, you can use the member name as requested, but this risks collisions.
        $originalName = $_FILES['filep']['name'];
        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
        $newFileName = uniqid() . '.' . $extension; 

        $targetPath = $uploadDir . $newFileName;

        if (move_uploaded_file($_FILES['filep']['tmp_name'], $targetPath)) {
            // Prepare the SQL statement to prevent SQL Injection
            $stmt = $pdo->prepare("INSERT INTO dbProfiles (nameMember, bandMember, photo, aboutMember, otherBands) VALUES (:name, :band, :photo, :about, :other)");
            
            $stmt->execute([
                ':name' => $nameMember,
                ':band' => $bandMember,
                ':photo' => $newFileName, // Store the new unique filename here
                ':about' => $aboutMember,
                ':other' => $otherBands
            ]);

            echo "Success: Member added and photo stored.";
        } else {
            throw new Exception("Failed to move uploaded file.");
        }
    }
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
} catch (Exception $e) {
    die("Upload error: " . $e->getMessage());
}
?>

Critical Implementation Details

The trade-off in your original schema is the use of varchar for the image path. This forces your application to manage file paths as strings rather than binary data. While this saves significant database space, it introduces a dependency on the filesystem. If you change the server's directory structure or rename the images folder, every record in your database becomes broken until you update the code to reflect the new path.

Another pitfall in your proposed form logic is the instruction: "The file name should be named after the Members name." If two users upload a photo for "John Doe" on the same day, the second upload will overwrite the first because move_uploaded_file replaces existing files with the same name. To avoid data loss, you must generate a unique filename (like using uniqid()) and store that in the database, regardless of the original client-side filename. This decouples your application's internal reference from the user's browser history.

Finally, ensure your images directory has the correct permissions (typically 755 or 775 depending on the server setup) so that the web server process can write to it. If the directory is not writable, move_uploaded_file will throw a warning, and your database insert will fail silently if error reporting is not set to exception mode. For a production CMS, consider integrating this logic into a framework like Laravel or using a library like Spatie's Image Manager, which handles these file persistence patterns more robustly than raw PHP scripts.

Our network