PHP MYSQL Multiple Database Connections

PHP MYSQL Using Two or More Database Connections

In vast majority of php applications, one database is sufficient to run the application. However, you could encounter a situation where you need to use two database connections because you want to sink user data. One such reason could be that you want to allow a user to login into another application from the current running application. Bridging the two logins can allow applications to connect and thus; you can do more. Another reason why you may want to use another database is that you just want to grab the data from a different application.

The code below shows how you can simply connect and select data from two databases. However, you could run insert, update and delete commands from either database.

include ("");

$command_a = "SELECT * FROM table_sort WHERE id > '1' ";
	$result_a = mysqli_query($db, $command_a);
	while($row_a = mysqli_fetch_assoc($result_a)){
	$firstnamea = trim($row_a['firstname']);
	echo "From Database #1: ".$firstnamea."<br/>";
	echo "<br/><br/>";
require ('');
	$command_b = "SELECT * FROM table_sort WHERE id > 1 ";
	$result_b = mysqli_query($db2, $command_b);
	while($row_b = mysqli_fetch_assoc($result_b)){
	$firstnameb = $row_b['firstname'];
	echo "From Database #2: ".$firstnameb."<br/>";