Is it possible to establish a database connection from the local machine to access file names and directories for downloading in PHP?
Yes, it is possible to establish a database connection from the local machine in PHP to access file names and directories for downloading. You can store the file names and directories in a database table and retrieve them using SQL queries. By establishing a database connection, you can easily fetch the necessary information and use it to create download links for the files.
<?php
// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "files_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve file names and directories from the database
$sql = "SELECT file_name, file_directory FROM files_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "File Name: " . $row["file_name"]. " - Directory: " . $row["file_directory"]. "<br>";
// Create download links for the files
echo '<a href="' . $row["file_directory"] . '">Download ' . $row["file_name"] . '</a><br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- What are common pitfalls to avoid when using PHP to manipulate dates and timestamps in database queries?
- What are the potential pitfalls of directly outputting the result of a MySQL query in PHP without proper handling?
- How can regular expressions (regex) be effectively used in PHP for parsing and extracting specific information from code comments?