Using PHP to upload file and add the path to MySQL database

Using PHP to upload file and add the path to MySQL database

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

Stefan Bogdanescu

Founder & Senior Architect

Resolving Index Errors in PHP File Uploads and Database Integration

When debugging a file upload script, the most common stumbling block isn't usually the logic of moving files or connecting to a database; it is how you access the data returned by $_FILES and $_POST. The source material provided demonstrates a classic pattern where the developer assumes a specific key name exists in the superglobals without verifying its presence. This assumption leads directly to the "Undefined index" errors seen when running the script.

In the upload.php file, the line $Filename=$_POST['Filename']; triggers an error because the form field name used in the HTML input tag is name="Filename". While this matches, PHP superglobals can be tricky. If the form submission fails or if there are encoding issues, accessing $_POST['Filename'] directly throws a warning if the index doesn't exist. However, looking closely at the debug output provided in the source material reveals the real culprit: a mismatch between the input name and the expected array key inside $_FILES.

The error log shows:

Array
(
    [Filename] => Array
        (
            [name] => Laserkanon.jpg
            ...
        )
)

Here, the top-level key in $_FILES is Filename. This matches the input name. However, inside that array, the keys are name, type, tmp_name, etc. The code attempts to access $_FILES['uploadedfile']['Filename']. The string 'uploadedfile' does not exist as a top-level key in the $_FILES array; the actual key is 'Filename'. This causes the script to crash before it can even attempt to echo the success message or move the file.

To fix this, you must align your variable access with the actual keys returned by PHP's internal functions. When using move_uploaded_file(), you pass $_FILES['Filename']['tmp_name'] as the source and construct the destination path using $_FILES['Filename']['name']. You should never try to access a non-existent key like 'uploadedfile'.

Furthermore, the database connection code in the snippet relies on the deprecated mysql_* functions. These were removed in PHP 7.0 due to security vulnerabilities and lack of support for prepared statements. If you are maintaining legacy code, this might run, but it is strongly recommended to migrate to mysqli or PDO. Using these modern extensions allows you to use parameterized queries, which prevents SQL injection attacks when inserting the $Filename and $Description.

Here is a corrected approach using mysqli that resolves the index errors and secures the database interaction:

<?php
// Set up error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

$target_dir = "pics/";
$filename = basename($_FILES["Filename"]["name"]);
$file_target_path = $target_dir . $filename;
$file_size = $_FILES["Filename"]["size"];
$allowed_types = array("jpeg", "jpg", "png", "gif"); // Define allowed types

// Check if file was uploaded via POST
if ($_FILES["Filename"]["error"] == 0) {
    // Validate file size and type
    $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (in_array($file_ext, $allowed_types) && $file_size < 5 * 1024 * 1024) { // 5MB limit
        
        // Connect to database using mysqli (PDO recommended for complex apps)
        $mysqli = new mysqli("localhost", "root", "", "altabotanikk");

        if ($mysqli->connect_error) {
            die("Connection failed: " . $mysqli->connect_error);
        }

        // Prepare statement to prevent SQL Injection
        $stmt = $mysqli->prepare("INSERT INTO picture (Filename, Description) VALUES (?, ?)");
        
        // Escape inputs safely or use bound parameters
        $filename_for_db = basename($_POST['Filename']); 
        $description = $_POST['Description'];

        $stmt->bind_param("ss", $filename_for_db, $description);

        if ($stmt->execute()) {
            echo "The file " . htmlspecialchars($filename) . " has been uploaded successfully.";
            
            // Move the physical file
            if (move_uploaded_file($_FILES["Filename"]["tmp_name"], $file_target_path)) {
                echo "File moved to server.";
            } else {
                echo "Sorry, there was a problem moving the file.";
            }
        } else {
            echo "Error: " . $stmt->error;
        }

        $stmt->close();
        $mysqli->close();
    } else {
        echo "Invalid file type or size.";
    }
} else {
    // Debugging the actual error code if upload fails
    echo "Upload Error Code: " . $_FILES["Filename"]["error"]; 
    echo "<pre>" . print_r($_FILES, true) . "</pre>";
}
?>

The form remains largely the same, ensuring the input name matches the array key used in PHP:

<form method="post" action="upload.php" enctype="multipart/form-data">
    <p>Photo:</p>
    <!-- Ensure name attribute matches $_FILES['Filename'] -->
    <input type="file" name="Filename" required> 
    <p>Description</p>
    <textarea rows="10" cols="35" name="Description"></textarea>
    <br/>
    <input TYPE="submit" name="upload" value="Add"/>
</form>

The primary takeaway is consistency. The key used to access $_FILES in your PHP code must match the name attribute of your HTML input exactly. If you debug using print_r($_FILES), always inspect the first-level keys before trying to drill down into properties like ['name'] or ['tmp_name']. Misinterpreting the structure of the superglobals is a frequent source of runtime errors that can be avoided with careful inspection of the array output.

Our network