What role does database interaction play in a PHP script that involves file uploads and link storage?
Database interaction plays a crucial role in a PHP script that involves file uploads and link storage by allowing us to store information about the uploaded files such as file names, file paths, and other relevant data. This information can then be retrieved from the database when needed, making it easier to manage and organize the uploaded files.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "uploads";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = $_FILES['file']['name'];
$file_path = 'uploads/' . $file_name;
// Move uploaded file to desired directory
move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
// Store file information in database
$sql = "INSERT INTO files (file_name, file_path) VALUES ('$file_name', '$file_path')";
$conn->query($sql);
}
?>
Related Questions
- What are the potential pitfalls of using XAMPP for developing a PHP program intended for production?
- Are there any best practices for organizing PHP code in relation to form elements like radio buttons?
- How can PHP beginners effectively troubleshoot errors related to image generation using GDLib functions?