Home >Backend Development >PHP Tutorial >How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?
How to Store File Name with Other Information While Uploading an Image to a Server Using PHP
Problem:
When uploading an image to a server, how can you ensure that the file name, along with other form data, are stored in a database?
Answer:
To store the file name and additional information from a form while uploading an image to a server using PHP, follow these steps:
Form:
Create a form that includes fields for the file upload and other data you want to store.
PHP Script:
Here's an example script:
<code class="php">// Database connection details $host = 'localhost'; $user = 'username'; $password = 'password'; $database = 'database_name'; // Connect to the database $conn = mysqli_connect($host, $user, $password, $database); // Get the form data, including the File $name = $_POST['nameMember']; $position = $_POST['bandMember']; $photo = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $otherBands = $_POST['otherBands']; // Insert data into the database $sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$position', '$photo', '$about', '$otherBands')"; if ($conn->query($sql) === TRUE) { // Upload the file to the server $target = "your directory" . $photo; if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { echo "The file $photo has been uploaded, and your information has been added to the database."; } else { echo "Sorry, there was a problem uploading your file."; } } else { echo "Error: " . $conn->error; } // Close the database connection $conn->close();</code>
The above is the detailed content of How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?. For more information, please follow other related articles on the PHP Chinese website!