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:
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!