Storing File Name in Database While Uploading Image
Question:
How can one store the file name and other form data in a database while uploading an image to a server using PHP?
Solution:
1. Form Structure:
Use the following HTML code to create a form that captures the required information:
<code class="html"><form method="post" action="addMember.php" enctype="multipart/form-data"> <p>Band Member Name:</p> <input type="text" name="nameMember"> <p>Member's Position:</p> <input type="text" name="bandMember"> <p>Photo:</p> <input type="hidden" name="size" value="350000"> <input type="file" name="photo"> <p>Other Information:</p> <textarea rows="10" cols="35" name="aboutMember"></textarea> <p>Other Bands:</p> <input type="text" name="otherBands" size=30> <input type="submit" name="upload" value="Add Member"> </form></code>
2. Server-Side Code:
Process the form data using the following PHP script:
<code class="php">// Database connection and selection $conn = mysqli_connect("host", "username", "password", "database"); if (!$conn) { die("Database connection failed: " . mysqli_connect_error()); } // Form data extraction $name = $_POST['nameMember']; $bandMember = $_POST['bandMember']; $photo = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $bands = $_POST['otherBands']; // Photo upload target directory $target = "directory/"; $target .= basename($photo); // Insert data into the database $sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$bandMember', '$photo', '$about', '$bands')"; $result = mysqli_query($conn, $sql); // Check for successful insertion if ($result) { // If successful, move the uploaded photo to the server if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { echo "File uploaded and data saved successfully."; } else { echo "Error uploading file."; } } else { echo "Error saving data."; } mysqli_close($conn);</code>
The above is the detailed content of How to Store File Names and Form Data in a Database While Uploading Images with PHP?. For more information, please follow other related articles on the PHP Chinese website!