What are some common mistakes that can lead to invalid MySQL connections when using PHP classes?

One common mistake that can lead to invalid MySQL connections when using PHP classes is not properly closing the connection after it has been used. This can result in reaching the maximum number of open connections allowed by MySQL, causing subsequent connections to fail. To solve this issue, always make sure to close the connection to MySQL after executing queries.

// Create a class for handling MySQL connections
class MySQLConnection {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);

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

    public function query($sql) {
        $result = $this->connection->query($sql);

        // Close the connection after executing the query
        $this->connection->close();

        return $result;
    }
}

// Example usage
$mysql = new MySQLConnection("localhost", "username", "password", "database");
$result = $mysql->query("SELECT * FROM table_name");