这些代码用于对不同的服务器执行相同的查询。我使用foreach
循环连接不同的服务器,并使用updateDB
函数执行查询。
我需要将失败的连接记录到数组中。
foreach ($lines as $value) {
$servername = $value;
$conn = new mysqli ($servername, $username, $password, $database);
if ($conn->connect_error) {
echo $servername."Connection failed:" . $conn->connect_error."<br>";
$errorMessage = array("Servername" => $servername , "Error" => $conn->connect_error);
}
else {
echo $servername." ".$database." Connected Succesfully <br>";
updateDB($data, $servername, $conn);
}
$conn-> close();
}
但是,数组仅保存失败连接的最后一条记录。
正确的echo
输出如下:
192.168.0.2 Connection failed: No route to host
192.168.0.3 Connection failed: No route to host
192.168.0.25 Connection failed: No route to host
192.168.0.47 Connection failed: No route to host
但是,当我print_r
我的数组$errorMessage
时,它仅显示:
Array ( [0] => 192.168.0.47 [1] => No route to host )
并且前3条记录不在数组内。
我知道
$ errorMessage = array(“ Servername” => $ servername,“ Error” => $ conn-> connect_error);
但是我已经搜索了,找不到解决方案。请帮忙。 TQ
答案 0 :(得分:3)
您需要在现有数组元素中添加新数组,而不是覆盖先前的数组。
$errorMessage[] = array("Servername" => $servername , "Error" => $conn->connect_error);
答案 1 :(得分:1)
您应该添加到数组中,而不要在每个循环中都写一个新的数组。
$errorMessages = array();
foreach ($lines as $value) {
$servername = $value;
$conn = new mysqli ($servername, $username, $password, $database);
if ($conn->connect_error) {
echo $servername."Connection failed: ".$conn->connect_error;
$errorMessages[] = array("Servername" => $servername , "Error" => $conn->connect_error);
} else {
echo $servername." ".$database." Connected Succesfully";
updateDB($data, $servername, $conn);
}
$conn-> close();
}
$errorMessages
将包含您想要的错误消息。
答案 2 :(得分:0)
个人始终使用数组推送:
array_push($errorMessages, array("Servername" => $servername , "Error" => $conn->connect_error));
这会将一个元素添加到数组的末尾。有关更多信息,请参见PHP Manual