I looked through a few threads to find an answer to this question but was unsuccessful.

I want to upload a file to my server and at the same time insert it's file name into my database. I've got the upload portion working just fine. Does anyone have a snippet of code that will insert a file name into a database? Thanks in advance!

Dani AI

Generated

already has the upload working and pointed to related threads. A concise, secure pattern is: validate the incoming file, generate a safe unique filename, move it to a controlled uploads folder, then insert that stored filename (or relative path) into the database using a prepared statement. This keeps binary data on disk and metadata in the DB, which is simpler and faster for most apps.

Example (minimal, illustrative):

<?php
// assume $pdo is a PDO instance with ERRMODE_EXCEPTION
if (!empty($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmp  = $_FILES['file']['tmp_name'];
    $orig = basename($_FILES['file']['name']);            // client name
    $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    // basic allow list
    $allowed = ['jpg','png','pdf','txt','docx'];
    if (!in_array($ext, $allowed)) exit('Bad file type');

    $safeName = uniqid('', true) . '.' . $ext;            // avoid collisions
    $dest = __DIR__ . '/uploads/' . $safeName;

    if (move_uploaded_file($tmp, $dest)) {
        $stmt = $pdo->prepare("INSERT INTO uploads (filename, original_name, uploaded_at) VALUES (?, ?, NOW())");
        $stmt->execute([$safeName, $orig]);
    } else {
        // handle move failure
    }
}

Notes and cautions: always check $_FILES['...']['error'], validate size/MIME (do not trust client MIME), store only sanitized basenames, keep uploads outside the webroot or deny script execution in that folder, and remove the file if the DB insert fails to avoid orphan files. Use prepared statements to prevent SQL injection and choose an appropriate column (VARCHAR(255) is typical for filenames). For specifics, see PHP's move_uploaded_file and PDO docs and the OWASP File Upload Cheat Sheet: move_uploaded_file PDO prepared statements OWASP File Upload Cheat Sheet.

This is great! Thanks for finding the thread so quickly. Guess I will have to look a little harder next time.

U r welcome ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.