PHP使用数组

时间:2017-11-19 11:34:31

标签: php arrays error-handling

这是我的代码

<?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 xPaw\SourceQuery\SourceQuery;

// 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 failed:没有这样的主机。
  注意:已经在 40 G:\ XAMPP \ htdocs \ PHP-Source-Query-master \ Examples \ list.php 中定义了常量SQ_SERVER_ADDR >

1 个答案:

答案 0 :(得分:0)

正在使用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);
}