How can PHP be used to delete a file from a table and folder simultaneously?
To delete a file from a table and folder simultaneously using PHP, you can first delete the file from the folder using the `unlink()` function, then delete the corresponding entry from the database table. Make sure to sanitize user input and handle errors properly to ensure the operation is successful.
<?php
// File path and filename to delete
$file_path = 'path/to/file/filename.txt';
// Delete file from folder
if (file_exists($file_path)) {
unlink($file_path);
echo "File deleted successfully from folder.";
} else {
echo "File does not exist in folder.";
}
// Delete entry from database table
$connection = new mysqli("localhost", "username", "password", "database");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "DELETE FROM table_name WHERE file_path = '$file_path'";
if ($connection->query($sql) === TRUE) {
echo "Record deleted successfully from table.";
} else {
echo "Error deleting record: " . $connection->error;
}
$connection->close();
?>