0
0
PhpHow-ToBeginner · 4 min read

How to Upload Image and Store in MySQL Using PHP

To upload an image and store it in MySQL using PHP, use an HTML form with enctype='multipart/form-data' to send the image file, then in PHP read the file content with file_get_contents() and save it as a BLOB in MySQL. Use prepared statements to securely insert the image data into a table with a BLOB column.
📐

Syntax

Uploading an image involves an HTML form and PHP code to handle the file. The key parts are:

  • <form enctype='multipart/form-data' method='POST'>: allows file upload.
  • $_FILES['image']['tmp_name']: temporary file path of the uploaded image.
  • file_get_contents(): reads the image file content.
  • MySQL table with a BLOB column to store image data.
  • Prepared statements to insert the image safely.
html
<form action="upload.php" method="POST" enctype="multipart/form-data">
  <input type="file" name="image" />
  <input type="submit" value="Upload" />
</form>
💻

Example

This example shows a complete PHP script to upload an image and store it in a MySQL database using PDO with prepared statements.

php
<?php
// upload.php

$host = 'localhost';
$db = 'testdb';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $imageTmpPath = $_FILES['image']['tmp_name'];
    $imageName = $_FILES['image']['name'];
    $imageType = $_FILES['image']['type'];

    if (is_uploaded_file($imageTmpPath)) {
        $imageData = file_get_contents($imageTmpPath);

        $sql = "INSERT INTO images (name, type, data) VALUES (:name, :type, :data)";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':name', $imageName);
        $stmt->bindParam(':type', $imageType);
        $stmt->bindParam(':data', $imageData, PDO::PARAM_LOB);

        if ($stmt->execute()) {
            echo 'Image uploaded and stored successfully.';
        } else {
            echo 'Failed to store image.';
        }
    } else {
        echo 'No valid image uploaded.';
    }
} else {
    echo 'Please upload an image file.';
}
?>
Output
Image uploaded and stored successfully.
⚠️

Common Pitfalls

  • Not setting enctype='multipart/form-data' in the form causes the file not to upload.
  • Trying to insert the file path instead of file content into the database.
  • Not using prepared statements can lead to SQL injection risks.
  • Uploading very large images without size checks can cause errors.
  • Forgetting to create the MySQL table with a BLOB column to store image data.
php
<?php
// Wrong: inserting file path string instead of file content
$sql = "INSERT INTO images (name, type, data) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_FILES['image']['name'], $_FILES['image']['type'], $_FILES['image']['tmp_name']]);

// Right: read file content and bind as LOB
$imageData = file_get_contents($_FILES['image']['tmp_name']);
$sql = "INSERT INTO images (name, type, data) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $_FILES['image']['name']);
$stmt->bindParam(2, $_FILES['image']['type']);
$stmt->bindParam(3, $imageData, PDO::PARAM_LOB);
$stmt->execute();
?>
📊

Quick Reference

Summary tips for uploading and storing images in MySQL with PHP:

  • Use enctype='multipart/form-data' in your HTML form.
  • Access the uploaded file via $_FILES['image']['tmp_name'].
  • Read file content with file_get_contents() before storing.
  • Use a MySQL table with a BLOB column for image data.
  • Use prepared statements with PDO::PARAM_LOB to insert image data safely.
  • Check file size and type to avoid errors and security issues.

Key Takeaways

Always use enctype='multipart/form-data' in your form to upload files.
Read the uploaded image file content with file_get_contents() before storing in MySQL.
Store images in a MySQL BLOB column using prepared statements to avoid SQL injection.
Check for upload errors and validate file size and type for security.
Use PDO with PDO::PARAM_LOB to safely insert binary image data.