【问题标题】:PHP Define variable with foreach from arrayPHP用数组中的foreach定义变量
【发布时间】:2017-11-19 11:34:30
【问题描述】:

这是我的代码

<?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 失败:不知道这样的主机。
通知:常量 SQ_SERVER_ADDR 已在 G:\XAMPP\htdocs\PHP-Source-Query-master\Examples\list.php 的第 40 行中定义

【问题讨论】:

    标签: php arrays error-handling


    【解决方案1】:

    由于您使用的是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);
    }
    

    【讨论】:

    • 谢谢!我试过这个但我得到了这个错误:无法创建套接字:php_network_getaddresses:getaddrinfo失败:没有这样的主机是已知的。
    • 检查您的主机是否有效
    • 数组中的地址有效。当我定义时它起作用了('SQ_SERVER_ADDR', '208.103.169.12');然而,它只适用于一个并且是硬编码的。
    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2016-05-22
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多