PHP使用数组中的foreach定义变量
这是我的密码PHP使用数组中的foreach定义变量,php,arrays,error-handling,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"; $r
<?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( );
由于您使用的是常量
它不能重新声明,因此对于服务器地址,请使用变量。按如下所示更改您的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( );
}
}
由于您使用的是常量
,因此无法重新声明,因此对于服务器地址,请使用变量。按如下所示更改您的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( );
}
}
谢谢我尝试了此操作,但出现了以下错误:无法创建套接字:php\u network\u getaddresses:getaddrinfo失败:没有已知的此类主机。请检查您的主机是否有效数组中的地址是否有效。当我定义('SQ_SERVER_ADDR','208.103.169.12')时,它起作用了;然而,当时它只与一个和硬编码的ofc。谢谢!我尝试了此操作,但出现了以下错误:无法创建套接字:php\u network\u getaddresses:getaddrinfo失败:没有已知的此类主机。请检查您的主机是否有效数组中的地址是否有效。当我定义('SQ_SERVER_ADDR','208.103.169.12')时,它起作用了;然而,当时它只与一个和硬编码的ofc。