PHP Foreach具有mysql_fetch_array服务器状态

时间:2016-08-24 19:42:42

标签: php

我试图创建一个cronjob脚本,它检查几个服务器的状态。 不知怎的,它只使用我表中的第一个ip。

$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");
$a = mysql_fetch_array($aQ);
foreach ($a as $value) {

        $timeout = "10";
        $ssh= @fsockopen("$value","22",$timeout);

         if($ssh) {
            $status = 1;
         }
         else {
            $status = 0;
         }

         $time = time();
        if(db::aQuery("UPDATE `gh_server_hosts` SET hostLastScanned='".$time."', hostLastStatus='".$status."' WHERE hostIp = '".$value."'")) {
                echo "scanned";
            } else {
                echo "error";
            }
}

2 个答案:

答案 0 :(得分:0)

你必须将mysql_fetch_array置于循环中以获取所有这样的记录:

$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");

while ($value = mysql_fetch_assoc($aQ)) {
    $timeout = "10";
    $ssh= @fsockopen($value['hostIp'],"22",$timeout);

    // Rest of your code
}

我使用mysql_fetch_assoc代替mysql_fetch_array来限制输出数组。另外,正如其他mysql_*所述,函数已被弃用,因此在PHP 5.5 +上运行此代码之前请更新代码...

答案 1 :(得分:-1)

mysql_fetch_assoc()代替mysql_fetch_array(),但请注意deprecation warning with mysql。 (除了安全问题,如果PHP升级到7.0,您的代码将失败。)