How to Store File Name in Database When Uploading Image with Other Form Data Using PHP
Problem:
You are creating a system where users can upload a photo and provide additional information that needs to be stored in a database. However, you encounter difficulties in storing the uploaded file's name along with the other form data.
Answer:
To effectively store the file name with other form data, follow these steps:
1. Modify the Form:
Add additional inputs for capturing the information you want to store in the database:
<form method="post" action="addMember.php" enctype="multipart/form-data"> ... <input type="text" name="nameMember"> <input type="text" name="bandMember"> <input type="file" name="photo"> <textarea name="aboutMember"></textarea> <input type="text" name="otherBands"> ... </form>
2. Process the Form:
Here's a sample code:
<?php // Get form data and connect to database $name = $_POST['nameMember']; $bandMember = $_POST['bandMember']; $pic = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $bands = $_POST['otherBands']; $connection = mysqli_connect("yourhost", "username", "password", "dbName"); // Insert data into database $query = "INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands) VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')"; mysqli_query($connection, $query); // Upload file to server if (move_uploaded_file($_FILES['photo']['tmp_name'], 'your directory/' . $pic)) { echo "File uploaded successfully and data added to database."; } else { echo "Error uploading file."; } ?>
By following these steps, you can successfully store the uploaded file name along with other form data in your database while using PHP.
The above is the detailed content of How to Efficiently Store Uploaded File Names with Other Form Data in a PHP Database?. For more information, please follow other related articles on the PHP Chinese website!