How can one securely write uploaded file names to a database in PHP to ensure proper sorting and logging?

When writing uploaded file names to a database in PHP, it is important to sanitize the file names to prevent SQL injection attacks and ensure proper sorting and logging. One way to securely write file names to a database is to use prepared statements with parameter binding to prevent SQL injection. Additionally, you can use functions like mysqli_real_escape_string to escape special characters in the file names before inserting them into the database.

// Assuming $fileName contains the uploaded file name

// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare the SQL statement with a placeholder for the file name
$stmt = $mysqli->prepare("INSERT INTO files (file_name) VALUES (?)");

// Bind the file name to the prepared statement
$stmt->bind_param("s", $fileName);

// Execute the statement
$stmt->execute();

// Close the statement and the database connection
$stmt->close();
$mysqli->close();