How can PHP developers optimize the process of deleting files from a MySQL database efficiently?

When deleting files from a MySQL database in PHP, developers can optimize the process by using the DELETE query with the WHERE clause to specify the file to be deleted. Additionally, developers should consider using prepared statements to prevent SQL injection attacks and improve performance.

<?php
// Connect to the database
$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);
}

// File to be deleted
$file_id = 1;

// Prepare and execute the DELETE query
$stmt = $conn->prepare("DELETE FROM files WHERE id = ?");
$stmt->bind_param("i", $file_id);
$stmt->execute();

// Check if the file was successfully deleted
if ($stmt->affected_rows > 0) {
    echo "File deleted successfully.";
} else {
    echo "Error deleting file.";
}

// Close the connection
$stmt->close();
$conn->close();
?>