PHP 定义变量与数组中的 foreach 一起



这是我的代码

<?php
$serverArray = []; 
$con=mysqli_connect("--","--","--","--");
// Check connection
if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
$sql="SELECT ipaddress FROM gmodservers";
$result=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($result)) {
    print_r($row);
    array_push($serverArray,$row);
    print_r($serverArray);
}

// Free result set
mysqli_free_result($result);
mysqli_close($con);
///ServerPull///
require __DIR__ . '/../SourceQuery/bootstrap.php';
use xPawSourceQuerySourceQuery;
// For the sake of this example
Header( 'Content-Type: text/plain' );
Header( 'X-Content-Type-Options: nosniff' );
// Edit this ->
define( 'SQ_SERVER_PORT', 27015 );
define( 'SQ_TIMEOUT',     1 );
define( 'SQ_ENGINE',      SourceQuery::SOURCE );
foreach ($serverArray as $value) {
define( 'SQ_SERVER_ADDR', $value );
// Edit this <-
$Query = new SourceQuery( );
try
{
    $Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );
    print_r( $Query->GetInfo( ) );
    print_r( $Query->GetPlayers( ) );
    print_r( $Query->GetRules( ) );
}
catch( Exception $e )
{
    echo $e->getMessage( );
}
}
$Query->Disconnect( );

我在 SQL 数据库中有 IP。我将 IP 移动到数组中。然后,我想使用底部的函数打印有关数组中所有 IP 地址的所有信息。但是,我收到此错误:

无法创建套接字: php_network_getaddresses: getaddrinfo 失败: 不知道这样的主机。
注意:常量SQ_SERVER_ADDR已经在 G:\XAMPP\htdocs\PHP-Source-Query-master\Examples\list.php40
行中定义

当您使用constant时 它不能被重新声明,所以对于服务器地址使用变量。 更改foreach循环,如下所示

foreach ($serverArray as $value) {
//define( 'SQ_SERVER_ADDR', $value );
$server_address = $value;
// Edit this <-
$Query = new SourceQuery( );
try
{
    $Query->Connect( $server_address, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );
    print_r( $Query->GetInfo( ) );
    print_r( $Query->GetPlayers( ) );
    print_r( $Query->GetRules( ) );
}
catch( Exception $e )
{
    echo $e->getMessage( );
}
}

编辑

在数据库结果的while循环中,您将整行添加到数组中,您只需要添加ipaddress

while ($row=mysqli_fetch_array($result)) {
    print_r($row);
    array_push($serverArray,$row['ipaddress']);
    print_r($serverArray);
}

最新更新