How can I avoid having to re-establish the database connection every time I call a function in my PHP class?
To avoid having to re-establish the database connection every time you call a function in your PHP class, you can establish the connection once in the constructor of your class and store the connection object as a class property. This way, the connection will be available to all methods within the class without the need to reconnect each time.
class DatabaseConnection {
private $connection;
public function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public function fetchData() {
$query = $this->connection->query('SELECT * FROM mytable');
return $query->fetchAll();
}
// Other methods that can use the $this->connection property
}
// Usage
$database = new DatabaseConnection();
$data = $database->fetchData();
Related Questions
- What are some common errors that developers may encounter when implementing CSV file validation in PHP?
- Are there alternative methods or libraries available for implementing captcha functionality in PHP, aside from the custom code provided?
- What are some best practices for organizing PHP code to avoid header modification errors?