Home >Database >Mysql Tutorial >How to Efficiently Store Uploaded Image Filenames in a Database Using PHP?

How to Efficiently Store Uploaded Image Filenames in a Database Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 16:05:16439browse

How to Efficiently Store Uploaded Image Filenames in a Database Using PHP?

How to Store File Name in Database While Uploading Image with PHP

Problem:

Uploading an image to a server and storing its filename in a database can be challenging. Additionally, integrating the image upload with the submission of other data from a form presents difficulties.

Solution:

Modified Form:

The updated form includes the following changes:

  • Adds a file upload input field named photo for the image.
  • Submit button is named upload.
  • Specifies a maximum file size of 35kb with name="size" value="350000".

PHP Processing Code:

The PHP code connects to the database and inserts both the uploaded image and the other form data.

  1. Database Connection and Data Insertion:

    // Connect to the database
    $connect = mysqli_connect("yourhost", "username", "password", "dbName");
    
    // Write the information to the database
    $query = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands)
    VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')";
    mysqli_query($connect, $query);
  2. Image Upload:

    // Image upload path
    $target = "your directory";
    $target = $target . basename($_FILES['photo']['name']);
    
    if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
        echo "The file has been uploaded, and your information has been added to the directory";
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }

The above is the detailed content of How to Efficiently Store Uploaded Image Filenames in a Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn