In the provided PHP script, what improvements can be made to enhance code readability, maintainability, and error handling in database interactions?

To enhance code readability, maintainability, and error handling in database interactions, it is recommended to use prepared statements to prevent SQL injection, utilize exception handling for better error management, and separate database connection logic into a separate function for reusability.

// Improved PHP script with enhanced code readability, maintainability, and error handling in database interactions

// Function to establish a database connection
function connectToDatabase() {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    return $conn;
}

// Using prepared statements to prevent SQL injection
$conn = connectToDatabase();
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "john_doe";
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process results
}

$stmt->close();
$conn->close();