What are the potential performance implications of creating a new connection vs. reopening an existing one in PHP?
Creating a new connection every time a script runs can lead to performance issues due to the overhead of establishing a connection. Reusing an existing connection can improve performance by reducing the time it takes to establish a connection.
// Create a function to establish a database connection if one doesn't already exist
function getDbConnection() {
static $conn;
if (!$conn) {
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
return $conn;
}
// Example usage
$conn = getDbConnection();
Related Questions
- Are there potential security risks associated with not using the PDO::PARAM_INT parameter in PHP prepared statements?
- What are the common pitfalls when sending multilingual data in HTML emails with PHP?
- What are some best practices for using xpath to parse tables in PHP, especially when retrieving specific columns like the first and last ones?