Home  >  Article  >  Backend Development  >  How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?

How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 06:20:02918browse

How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?

How to Store File Name with Other Information While Uploading an Image to a Server Using PHP

Problem:

When uploading an image to a server, how can you ensure that the file name, along with other form data, are stored in a database?

Answer:

To store the file name and additional information from a form while uploading an image to a server using PHP, follow these steps:

Form:

Create a form that includes fields for the file upload and other data you want to store.

PHP Script:

  1. Connect to your database.
  2. Get the information from the form, including the file name.
  3. Insert the information into your database table, including the file name.
  4. Use the move_uploaded_file() function to move the uploaded image to its intended destination.

Here's an example script:

<code class="php">// Database connection details
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'database_name';

// Connect to the database
$conn = mysqli_connect($host, $user, $password, $database);

// Get the form data, including the File
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$photo = $_FILES['photo']['name'];
$about = $_POST['aboutMember'];
$otherBands = $_POST['otherBands'];

// Insert data into the database
$sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$position', '$photo', '$about', '$otherBands')";

if ($conn->query($sql) === TRUE) {
    // Upload the file to the server
    $target = "your directory" . $photo;
    if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
        echo "The file $photo has been uploaded, and your information has been added to the database.";
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
} else {
    echo "Error: " . $conn->error;
}

// Close the database connection
$conn->close();</code>

The above is the detailed content of How to Store Image File Names and Other Form Data in a Database During 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