How to store images in mysql database using php

How to store images in mysql database using php

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

Stefan Bogdanescu

Founder & Senior Architect

Storing Images Directly in MySQL: Why You Shouldn't and How to Do It Right

Your current implementation correctly handles file uploads by saving images to a directory on the server. The logic using move_uploaded_file is standard and reliable for small-scale applications or simple prototypes. However, attempting to store the actual image binary data inside a MySQL database column is generally a bad architectural decision. While it is technically possible to insert a large BLOB (Binary Large Object) into a TINYBLOB, MEDIUMBLOB, or LONGBLOB field, doing so introduces significant performance bottlenecks that degrade your application as soon as you scale beyond trivial use cases.

The primary issue lies in how modern web servers and databases handle large data. When an image is uploaded to a file system, the web server processes the request, writes the file to disk, and then hands over control. The database simply stores a reference (a filename or path) to that location. This separation of concerns allows the web server to serve static assets efficiently via serve_static_file or similar directives, offloading bandwidth and CPU usage from the application logic. In contrast, storing images in the database forces every request to query the database, retrieve the binary data, and stream it back to the client through the database connection. Database connections are expensive resources; saturating them with image streaming will drastically increase latency and slow down all other queries on your server.

If you proceed with this approach despite the warnings, you must ensure your database schema supports large binaries. You should define the column type as LONGBLOB to accommodate images larger than 16MB or those exceeding standard row size limits found in older MySQL configurations. Furthermore, you need to consider the storage engine. If you are using InnoDB, you must enable the innodb_large_prefix variable if your version of MySQL is older (prior to 5.6.4) and you intend to use large text or binary columns with a non-default page size.

Here is how you would technically implement this in PHP, assuming you have accepted the trade-offs regarding performance:

$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
$fileData = file_get_contents($_FILES["imageUpload"]["tmp_name"]); // Read binary data

// Prepare the insert query
$stmt = $pdo->prepare("INSERT INTO images (filename, image_data) VALUES (?, ?)");

// Bind parameters: 's' for string (filename), 'b' for binary (image data)
$stmt->bindParam(':filename', basename($_FILES["imageUpload"]["name"]), PDO::PARAM_STR);
$stmt->bindParam(':image_data', $fileData, PDO::PARAM_LOB);

if ($stmt->execute()) {
    echo "Image stored successfully.";
} else {
    echo "Error storing image: " . $stmt->errorInfo()[0];
}

To retrieve and display the image, you must fetch the binary data from the database and output it with the correct MIME type. A common mistake is fetching the data as a string and echoing it directly; this often results in garbled text or 403 Forbidden errors because the browser interprets the content as text rather than an image.

$stmt = $pdo->prepare("SELECT filename, image_data FROM images WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch();

if ($row) {
    header('Content-Type: image/jpeg'); // Or appropriate MIME type
    echo $row['image_data'];
}

This method works for tiny datasets, such as storing a single avatar per user in a small internal tool. However, for any production application handling galleries or user-generated content, the overhead of writing and reading large BLOBs becomes the limiting factor. The industry standard remains storing files on disk or in an object storage service like AWS S3, while keeping only the metadata (filename, MIME type, upload date) in the database. This hybrid approach ensures that your database remains responsive for business logic while the file system handles the heavy lifting of serving assets.

For developers using the Laravel framework, this pattern is even more critical. While you can use Storage::disk('db')->put($path, $fileContent) to simulate a similar workflow within a single disk abstraction, it is rarely recommended for production environments. If your project requires robust media management, consider leveraging the LaravelCompany ecosystem for guidance on best practices regarding file storage strategies and scaling considerations.

Our network