How can PHP code be optimized for handling file uploads and database interactions in a guestbook application?

To optimize PHP code for handling file uploads and database interactions in a guestbook application, it is important to properly validate and sanitize user input, use prepared statements to prevent SQL injection attacks, and handle file uploads securely to prevent malicious uploads.

// Example code for handling file uploads in a guestbook application
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        // File uploaded successfully, now save file path to database
        $filePath = $uploadFile;
        
        // Insert file path into database using prepared statement
        $stmt = $pdo->prepare("INSERT INTO guestbook (file_path) VALUES (:file_path)");
        $stmt->bindParam(':file_path', $filePath);
        $stmt->execute();
        
        echo "File uploaded and saved to database successfully.";
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "Error uploading file: " . $_FILES['file']['error'];
}