How can one optimize PHP code to prevent multiple unnecessary database connections within a script?

To optimize PHP code and prevent multiple unnecessary database connections within a script, you can implement a database connection pooling mechanism. This involves creating a single database connection object and reusing it throughout the script instead of establishing a new connection each time a query needs to be executed. By pooling connections, you can improve performance and reduce resource consumption.

// Create a class for managing database connections
class Database {
    private static $connection;

    public static function getConnection() {
        if (!self::$connection) {
            self::$connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
        }
        return self::$connection;
    }
}

// Example usage
$db = Database::getConnection();
$stmt = $db->prepare('SELECT * FROM users');
$stmt->execute();
$results = $stmt->fetchAll();