How to upload image and save path to database?

How to upload image and save path to database?

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

Stefan Bogdanescu

Founder & Senior Architect

Why Storing Image Data in the Database Is a Bad Idea

The core issue preventing your upload form from working isn't a bug in PHP's $_FILES array or a syntax error in your SQL query. It is a fundamental misunderstanding of how file uploads and database storage interact. Your code attempts to read the raw binary data of an image, escape it with addslashes, and insert that massive blob directly into a standard text column. This approach fails immediately because databases are not designed to handle arbitrary binary streams as strings, and more critically, you are storing the file content instead of storing the location where the content lives on your server.

When your script prints "NO IMAGE SELECTED", it indicates that $_FILES['image'] is empty or invalid. This usually happens if the form action attribute doesn't point to a handler that processes the upload, or if the file size exceeds limits. However, assuming the form submission reaches PHP, the logic inside your INSERT statement is where the architecture breaks down.

The Two-Step File Upload Pattern

To successfully upload an image and save its path to a database, you must separate the physical file storage from the data storage. This is known as the two-step process:

  1. Physical Storage: Move the uploaded file from the user's temporary directory (usually /tmp) to a permanent location on your web server, such as an uploads/ folder within your project.
  2. Logical Storage: Record the relative path (e.g., uploads/photo.jpg) and metadata (like filename or timestamp) in your database table.

Your current implementation tries to bypass step one entirely. By using fread() to load the entire file into memory, you risk crashing the script on large images due to excessive memory consumption. Furthermore, inserting binary data via a string column often results in data corruption or encoding errors because databases treat strings as text unless explicitly cast as binary types (like BLOB), which complicates querying and rendering later.

Implementing the Correct Workflow

Here is how you should structure the upload handler. First, ensure your gallery.php (or a dedicated upload_handler.php) has a writable directory for images. You can configure PHP to allow uploads in php.ini:

upload_max_filesize = 10M
post_max_size = 12M

In your form, the action should point to this handler:

<form enctype="multipart/form-data" action="upload_handler.php" method="post">
    <input name="image" accept="image/jpeg" type="file">
    <input value="Submit" type="submit">
</form>

In the upload_handler.php, you need to handle the file movement and generate a safe filename. Avoid using the original client filename directly to prevent path traversal attacks. Instead, generate a unique name:

<?php
// Include database connection
include 'conf.php';

if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['image'];
    $tmpName = $file['tmp_name'];
    
    // Generate a safe, unique filename to avoid collisions and path issues
    $uniqueName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
    $destinationPath = 'uploads/' . $uniqueName;

    if (move_uploaded_file($tmpName, $destinationPath)) {
        // Now store only the relative path in the database
        $query = "INSERT INTO eikones (path) VALUES ('$destinationPath')";
        
        // Note: In production, use prepared statements to prevent SQL injection
        // Example with PDO:
        // $stmt = $pdo->prepare("INSERT INTO eikones (path) VALUES (?)");
        // $stmt->execute([$destinationPath]);

        print "DONE";
    } else {
        print "MOVE FAILED";
    }
} else {
    print "NO IMAGE SELECTED";
}
?>

Updating Your Display Logic

Once the file is saved to uploads/ and the path is stored in the path column, your existing gallery loop will work perfectly. You simply need to ensure the database query retrieves the relative path and concatenates it with your web root if necessary.

In your original code:

if(isset($row[ "path" ])) {
    $path= $row[ "path" ];
}
// ...
echo "<img src=\"$path\" alt=\"Pic\">";

This assumes $row['path'] contains the full URL or a path relative to the current document root. If your database column stores just uploads/photo.jpg, ensure your PHP script renders it correctly, perhaps using:

echo "<img src=\"/your-project-root/{$path}\" alt=\"Pic\">";

Security and Modern Practices

Before adopting this pattern in a new project, consider the security implications. Storing binary data in a database column is inefficient and slows down queries. Always store file paths as strings. Additionally, never trust user input for filenames; always sanitize and randomize them to prevent attackers from overwriting critical system files.

If you are building a larger application or migrating legacy systems like the one described here, frameworks like Laravel provide robust storage managers that handle these file operations securely out of the box. For instance, https://laravelcompany.com offers resources on how modern applications handle asset management without reinventing the wheel with raw PHP functions.

By shifting from storing images in the database to storing paths to the database, you gain flexibility, improve performance, and adhere to standard web architecture principles.

Our network