Deprecated: Automatic conversion of false to array is deprecated in /home/xk106539/domains/saotn.org/public_html/wp-content/plugins/yet-another-stars-rating/includes/yasr-includes-functions.php on line 337

Connect to multiple MySQL servers in a for and foreach loop

Date posted: 2014-03-05
Last updated: 2026-05-14

Check the connectivity of multiple MySQL servers, and connect to the servers in a loop. Here are two example code snippets




Deprecated: Automatic conversion of false to array is deprecated in /home/xk106539/domains/saotn.org/public_html/wp-content/plugins/yet-another-stars-rating/includes/yasr-includes-functions.php on line 337

Suppose you want to check the connectivity of multiple MySQL servers, and connect to the servers in a loop. Here are two example code snippets. One that uses a for loop and one using a foreach loop.

Connect to multiple MySQL servers in a foreach loop

function checkMysql() {
	$mysql_nodes = array(
		"server-01",
		"server-02",
		"server-03",
		"server-04",
		"server-05",
		"server-06",
		"server-07",
		"server-08",
		"server-09",
		"server-10",
		"server-11"
		);
	foreach ($mysql_nodes as $mysql_node) {
		$mysqli = new mysqli($mysql_node, "username", "passw0rd", "database");
		if($result = $mysqli->query("SHOW TABLES")) {
			echo $mysql_node. "checked";
			mysqli_free_result($result);
		}
		$mysqli->close();
	}
}

Connect to multiple MySQL servers in a for loop

function checkMysql() {
	$mysql_nodes = array(
		"server-01",
		"server-02",
		"server-03",
		"server-04",
		"server-05",
		"server-06",
		"server-07",
		"server-08",
		"server-09",
		"server-10",
		"server-11"
	);
	for ($i = 0; $i < sizeof($mysql_nodes); ++$i) {
		$mysqli = new mysqli($mysql_node, "username", "passw0rd", "database");
		if($result = $mysqli->query("SHOW TABLES")) {
			echo $mysql_node. "checked";
			mysqli_free_result($result);
		}
		$mysqli->close();
	}
}

Rate this post!

Leave a Comment



Deprecated: Automatic conversion of false to array is deprecated in /home/xk106539/domains/saotn.org/public_html/wp-content/plugins/yet-another-stars-rating/includes/yasr-includes-functions.php on line 337
Share via
Copy link