What are some best practices for managing MySQL connections in PHP scripts?
Managing MySQL connections in PHP scripts involves ensuring that connections are efficiently opened and closed to prevent resource exhaustion. Best practices include reusing connections where possible, using connection pooling, and closing connections when they are no longer needed.
// Create a function to establish a MySQL connection
function getDBConnection(){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Example of using the connection
$conn = getDBConnection();
// Close the connection when done
$conn->close();