Home  >  Article  >  Backend Development  >  How to Store File Names and Form Data Together During Image Uploads with PHP?

How to Store File Names and Form Data Together During Image Uploads with PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 04:25:02655browse

How to Store File Names and Form Data Together During Image Uploads with PHP?

Storing File Name and Additional Form Data in Database While Uploading Image to Server Using PHP

This article addresses the challenge of storing the file name of an uploaded image along with other form data in a database.

The Form

The HTML form to be used includes fields for entering band member details (name, position, photo, etc.) and a file upload input for the band member photo.

PHP Processing

The PHP script performs the following steps:

  • Extraction of Form Data: Information entered into the form is extracted and stored in variables.
  • Database Connection: A connection to the database is established.
  • Database Insertion: An SQL query is executed to insert the form data, including the file name, into the database table.
  • File Upload: The uploaded file is moved to a designated directory on the server using the move_uploaded_file() function.
  • Confirmation: Upon successful upload and database insertion, a confirmation message is displayed.

Sample Code

The following PHP script incorporates the concepts discussed above:

<code class="php"><?php

// Directory for image storage
$target = "images/";
$target_file = $target . basename($_FILES['photo']['name']);

// Retrieve form data
$nameMember = $_POST['nameMember'];
$bandMember = $_POST['bandMember'];
$aboutMember = $_POST['aboutMember'];
$otherBands = $_POST['otherBands'];

// Database connection
$mysqli = new mysqli("localhost", "username", "password", "databaseName");

// Database insertion query
$query = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands)
VALUES ('$nameMember', '$bandMember', '$target_file', '$aboutMember', '$otherBands')";
$result = $mysqli->query($query);

// Image upload
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file)) {
    echo "File uploaded successfully and data saved in database.";
} else {
    echo "Error uploading file.";
}

?></code>

Note: The database connection details, as well as the table name, should be modified to match your specific environment.

The above is the detailed content of How to Store File Names and Form Data Together During Image Uploads with 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