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!