How can you write a file name from an upload form into a database using PHP?

When a file is uploaded through a form in PHP, you can retrieve the file name using the $_FILES superglobal array and then store it in a database. To do this, you need to establish a database connection, sanitize the file name to prevent SQL injection, and then execute an SQL query to insert the file name into the database.

<?php

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the uploaded file name
$fileName = $_FILES['file']['name'];

// Sanitize the file name
$fileName = $conn->real_escape_string($fileName);

// Insert the file name into the database
$sql = "INSERT INTO files (file_name) VALUES ('$fileName')";

if ($conn->query($sql) === TRUE) {
    echo "File name inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>