Are there any best practices for error handling in PHP when including files based on database queries?

When including files based on database queries in PHP, it is important to handle errors gracefully to prevent potential security vulnerabilities or unexpected behavior. One best practice is to validate the input from the database query before including the file to ensure it is safe and exists. Additionally, using try-catch blocks or error handling functions can help catch any errors that may occur during the file inclusion process.

// Example of error handling when including files based on database queries
$query = "SELECT file_path FROM files WHERE id = $file_id";
$result = mysqli_query($connection, $query);

if($result) {
    $row = mysqli_fetch_assoc($result);
    $file_path = $row['file_path'];

    if(file_exists($file_path)) {
        include($file_path);
    } else {
        echo "File does not exist";
    }
} else {
    echo "Error executing query";
}