What are the best practices for structuring PHP code to handle multiple database connections on the same page?
When handling multiple database connections in PHP on the same page, it is important to properly structure your code to avoid conflicts and ensure efficient management of the connections. One common approach is to create separate instances of database connection objects for each database, using different variable names to distinguish between them. This helps prevent mix-ups and ensures that each connection is used appropriately within its scope.
// Establish connection to Database 1
$host1 = 'localhost';
$username1 = 'user1';
$password1 = 'password1';
$database1 = 'database1';
$connection1 = new mysqli($host1, $username1, $password1, $database1);
// Establish connection to Database 2
$host2 = 'localhost';
$username2 = 'user2';
$password2 = 'password2';
$database2 = 'database2';
$connection2 = new mysqli($host2, $username2, $password2, $database2);
// Use $connection1 for operations on Database 1
// Use $connection2 for operations on Database 2