Home >Database >Mysql Tutorial >How to Efficiently Store Image Filenames in a Database During an Upload?

How to Efficiently Store Image Filenames in a Database During an Upload?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 00:02:10893browse

How to Efficiently Store Image Filenames in a Database During an Upload?

Storing Filenames in a Database while Uploading Images

Challenge:

Uploading an image to a server and storing its filename in a database while capturing additional form data poses a common challenge for web developers.

Solution:

1. Form Modifications:

The form used for image upload and data collection should include:

<form method="post" action="addMember.php" enctype="multipart/form-data">
    <!-- ... Additional form fields here ... -->
    <input type="hidden" name="size" value="350000">
    <label for="photo">Photo:</label>
    <input type="file" name="photo">
    <!-- ... Additional form fields here ... -->
</form>

2. PHP Code for Processing:

The PHP code processes the form data and uploads the image to the server:

<?php
// Connect to database
$connection = mysqli_connect("yourhost", "username", "password", "dbname");

// Retrieve form data
$name = $_POST['nameMember'];
$bandMember = $_POST['bandMember'];
$pic = $_FILES['photo']['name'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];

// Upload image
if (move_uploaded_file($_FILES['photo']['tmp_name'], "your-upload-path/$pic")) {
    // Insert data into database
    $query = "INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands) VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')";
    $result = mysqli_query($connection, $query);

    // Check if data was inserted successfully
    if ($result) {
        echo "Data and image uploaded successfully";
    } else {
        echo "Error uploading data or image: " . mysqli_error($connection);
    }
} else {
    echo "Error uploading image";
}

// Close database connection
mysqli_close($connection);
?>

The above is the detailed content of How to Efficiently Store Image Filenames in a Database During an Upload?. 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