How can the code be modified to properly handle the database connection?

The issue with the code is that the database connection is not being properly handled, leading to potential errors and security vulnerabilities. To solve this, we can create a separate function to establish the database connection and call it whenever needed in the code.

<?php

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

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

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

    return $conn;
}

// Example of how to use the connectToDatabase function
$conn = connectToDatabase();

// Rest of the code using the $conn object for database operations
// ...

?>