How to do if and else between 2 variables with output in a third?

0

I'm sorry but I had to rewrite all my question because it was not being objective enough to make me understand, when I omit code as it was the previous case is not to hide something is just to be able to perceive what they respond to me within my limitations of programming, in any case as soon as the platform is ready I will make it available online.

In this first file will be available the variables to be able to be changed to make the connections between the 3 servers the demo is for server 1.

#/pasta/config.php
<?PHP
//Atenção ao configurar este ficheiro pois é igual para os 3 servidores
//e terá que ter em mente em que servidor o esta a configurar
//porque tem que descomentar o $serverip correspondente e entre as aspas colocar o seu ip interno de sua rede
//e em $dbL colocar entre as aspas o numero correspondente ao servidor que escolheu 1, 2 ou 3.

$dbL = "1";// Que servidor é este? 1, 2 ou 3.

$serverip1  = "10.0.0.101";    // Ip interno Mysql se for o servidor 1
$db_porta1    = "3306";        // Porta Mysql servidor 1
$db_user1     = "dns";         // Utilizador Mysql servidor 1
$db_password1 = "123456";      // Senha Mysql servidor 1
$db_name1     = "dns";         // Nome base dados Mysql servidor 1

//$serverip2 = "10.0.0.102";   // Ip interno Mysql se for o servidor 2
$db_porta2    = "3306";        // Porta Mysql servidor 2
$db_user2     = "dns";         // Utilizador Mysql servidor 2
$db_password2 = "123456";      // Senha Mysql servidor 2
$db_name2     = "dns";         // Nome base dados Mysql servidor 2

//$serverip3 = "10.0.0.103";   // Ip interno Mysql se for o servidor 3
$db_porta3    = "3306";        // Porta Mysql servidor 3
$db_user3     = "dns";         // Utilizador Mysql servidor 3
$db_password3 = "123456";      // Senha Mysql servidor 3
$db_name3     = "dns";         // Nome base dados Mysql servidor 3
?>

The next 3 files are updated every 60 seconds and the ips have already been checked before entering the servers.

#/pasta/connect/ipserver1.php
<?PHP $s_ipserver11 = "xx.246.142.235";?>

#/pasta/connect/ipserver2.php
<?PHP $s_ipserver22 = "xx.246.142.245";?>

#/pasta/connect/ipserver3.php
<?PHP $s_ipserver33 = "xx.246.142.255";?>

To not be doing 4 includes in all the files you need, I created the following one.

#/pasta/connect/ipservers.php
<?PHP
include_once("/pasta/config.php");
include_once("/pasta/connect/ipserver1.php");
include_once("/pasta/connect/ipserver2.php");
include_once("/pasta/connect/ipserver3.php");
?>

This will be the file of this question where I want to input 2 variables or not and output a third for each connection.

#/pasta/connect/convencao.php
<?PHP
include_once("/pasta/connect/ipservers.php");
//Se existir variável $serverip1 ler valor se não ler valor de $s_ipserver11 mas se existirem as duas ler sempre $serverip1 e responder em $ip1.
//Se existir variável $serverip2 ler valor se não ler valor de $s_ipserver22 mas se existirem as duas ler sempre $serverip2 e responder em $ip2.
//Se existir variável $serverip3 ler valor se não ler valor de $s_ipserver33 mas se existirem as duas ler sempre $serverip3 e responder em $ip3.
if( isset( $serverip1 ) and isset( $s_ipserver11 ) )
{
$ip1 = $serverip1;
}
else
{
if( isset( $serverip1 ) )
$ip1 = $serverip1;
if( isset( $s_ipserver11 ) )
$ip1 = $s_ipserver11;
}

if( isset( $serverip2 ) and isset( $s_ipserver22 ) )
{
$ip2 = $serverip2;
}
else
{
if( isset( $serverip2 ) )
$ip2 = $serverip2;
if( isset( $s_ipserver22 ) )
$ip2 = $s_ipserver22;
}

if( isset( $serverip3 ) and isset( $s_ipserver33 ) )
{
$ip3 = $serverip3;
}
else
{
if( isset( $serverip3 ) )
$ip3 = $serverip3;
if( isset( $s_ipserver33 ) )
$ip3 = $s_ipserver33;
}

$s_ipserver1 = $ip1;
$s_ipserver2 = $ip2; //Coloquei estas 3 variáveis para dar a entender o que preciso mas podem ser apagadas.
$s_ipserver3 = $ip3;
?>

Below are the various forms of linking to imply what I need.

Connection to server 1

#/pasta/connect/connectserver1.php
<?PHP
include_once("/pasta/connect/convencao.php");
$db_host1     = "$s_ipserver1:$db_porta1";
$db_link1     = mysql_connect($db_host1, $db_user1, $db_password1) or die (mysql_error ());
$db_connect1  = mysql_select_db($db_name1, $db_link1);
?>

Connection to server 2

#/pasta/connect/connectserver2.php
<?PHP
include_once("/pasta/connect/convencao.php");
$db_host2     = "$s_ipserver2:$db_porta2";
$db_link2     = mysql_connect($db_host2, $db_user2, $db_password2) or die (mysql_error ());
$db_connect2  = mysql_select_db($db_name2, $db_link2);
?>

Connection to server 3

#/pasta/connect/connectserver3.php
<?PHP
include_once("/pasta/connect/convencao.php");
$db_host3     = "$s_ipserver3:$db_porta3";
$db_link3     = mysql_connect($db_host3, $db_user3, $db_password3) or die (mysql_error ());
$db_connect3  = mysql_select_db($db_name3, $db_link3);
?>

Variables for connecting to the local server

#/pasta/connect/connectserverLsub.php
<?php 
include_once("/pasta/connect/convencao.php");
$ipserver  = 's_ipserver'. $dbL;
$porta     = 'db_porta'. $dbL;
$user      = 'db_user'. $dbL;
$password  = 'db_password'. $dbL;
$name      = 'db_name'. $dbL;
?>

Local server connection

#/pasta/connect/connectserverL.php
<?PHP
include_once("/rjpdns/connect/connectserverLsub.php");
$host         = $$ipserver . ':'. $$porta;
$link         = mysql_connect($host, $$user, $$password) or die (mysql_error ());
$db_connect   = mysql_select_db($$name, $link);
?>

I hope this time to have exposed and improved my doubts.

    
asked by anonymous 11.09.2014 / 08:50

4 answers

8

I'm not sure if that's what you want. You need to know what type are the $ ip1 and $ ip2 - whether they are bool or if they are the real ips. Tell me to adjust the question.

Option 1:

if( isset( $ip1 ) ){
    $ip3 = $ip1;
}elseif( isset( $ip2 ) ){
    $ip3 = $ip2;
}

Option 2:

Note that if $ ip1 and $ ip2 contain value (other than null), it will always return the last if due to the overlapping of true conditions.

$ips = array( $ip1 , $ip2 );
foreach( $ips as $val )
{
    if( $val )
    $ip3 = $val;
}

Option 3:

Solving overlap in case of two real ips.

if( isset( $ip1 ) and isset( $ip2 ) )
{
    // os dois estão corretos, vou usar o primeiro 'ip-1'
    $ip3 = $ip1;
}
else
{
    if( isset( $ip1 ) ){
        $ip3 = $ip1;
    }elseif( isset( $ip2 ) ){
        $ip3 = $ip2;
    }
}

Option 4:

I consider it a very practical option. You will have the $ ips variable with an array containing the $ ip1 and $ ip2 and then just use array_filter to filter all values that are null , and the usage will be the zero index $ips[0] - the first index that contains a value. Very simple to use.

$ip1 = 1;
$ip2 = 2;

$ips = array_filter( array( $ip1 , $ip2 ) );
$ip3 = $ips[0];

Update following instructions from the author's edition

// se existir $serverip1 e $s_ipserver11, usaremos $serverip1
if( isset( $serverip1 ) and isset( $s_ipserver11 ) )
{
    $ip1 = $serverip1;
}
else
{
    // se existir APENAS $serverip1
    if( isset( $serverip1 ) )
    $ip1 = $serverip1;

    // se existir APENAS $s_ipserver11
    if( isset( $s_ipserver11 ) )
    $ip1 = $s_ipserver11;
}
    
11.09.2014 / 09:11
0

Try to do so

    include_once("/pasta/ip1.php");
    include_once("/pasta/ip2.php");


    function validar_ips($ip1,$ip2){

         //verifica de o ip é válido
            $ip1 = (filter_var("111.111.111.111", FILTER_VALIDATE_IP)) ? "111.111.111.111" : FALSE;
            //verifica se o ip é válido
            $ip2 = (filter_var("222.222.222.222", FILTER_VALIDATE_IP)) ? "222.222.222.222" : FALSE;
            $ip3 = NULL;

            //se o ip não for válido então ip3 = ip2
            if(!$ip3=$ip1)
               $ip3=$ip2;

            //se nenhum dos ip for válido para a execução
            // aqui optei por filter_var para ter mesmo a certeza que tenho um ip válido
            if(!filter_var($ip3, FILTER_VALIDATE_IP))
             return NULL;

            return $ip3;
}

           $db_host1     = validar_ips($ip1,$ip2);
           $db_connect1  = mysqli_connect($db_host1, $db_user1, $db_password1, $db_name1,$db_porta1) or die (mysqli_error ());
    
11.09.2014 / 12:02
0

I understand that you will receive the 2 IPs, but at some point the IP 1, even if it is filled correctly it will not respond to the mysql connection call, so you should try to connect with IP 1 and in case of errors try on IP 2, I think something like this should work:

<?PHP
include_once("/pasta/connect.php");

foreach(array($ip1,$ip2) as $db_host1) {
    $db_connect1 = @mysqli_connect($db_host1, $db_user1, $db_password1, $db_name1, $db_porta1);
    if ($db_connect1) break;
}

if (!$db_connect1) die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());

?>

Note: I tested it here and it works fine, the only detail is that if IP 1 is invalid, there is a delay until it goes to IP 2. See if it is not better you try IP 2 first and then move on the IP 1.

    
11.09.2014 / 13:08
0

Let's see if this is what you want. To understand better, some considerations:

a) In /pasta/config.php all verifiable are a feature of a server then it is best to group them into an array. So we are sure that all belong to the same server. So it looks like this:

$server1 = array(

   "serverip"  => "10.0.0.101",    // Ip interno Mysql se for o servidor 1
   "db_porta"    => "3306",        // Porta Mysql servidor 1
   "db_user"     => "dns",         // Utilizador Mysql servidor 1
   "db_password" => "123456",     // Senha Mysql servidor 1
   "db_name"     => "dns",

);

$server2 = array(

   "serverip"  => "10.0.0.102",    // Ip interno Mysql se for o servidor 1
   "db_porta"    => "3306",        // Porta Mysql servidor 1
   "db_user"     => "dns",         // Utilizador Mysql servidor 1
   "db_password" => "123456",     // Senha Mysql servidor 1
   "db_name"     => "dns",

);

$server3 = array(

   "serverip"  => "10.0.0.102",    // Ip interno Mysql se for o servidor 1
   "db_porta"    => "3306",        // Porta Mysql servidor 1
   "db_user"     => "dns",         // Utilizador Mysql servidor 1
   "db_password" => "123456",     // Senha Mysql servidor 1
   "db_name"     => "dns",

);

b) Regarding the /pasta/connect/convencao.php file. Repeated code has been grouped into functions. I have as a rule, not trusting the data parameters to be sure of the output of the function. That's why, oddly enough, I checked the validity of the ips again. Here I give up performance and use more features to get output consistency.

c) I did not understand correctly connect to the first available server or if one of the three is not available to connect to another server. As it is the case I think this solution is for the two situations or some more. With these functions it tests the possibility to connect to any server and can later use the return array to connect to the database.

d) I did not debug the code.

/**
* vejo se consigo conectar a um servidor e guardo o ip na array de retorno. Se 
* conseguir *conectar gravo ao conexão e a tabela da array de retorno
*
* @param array $server - características do servidor
* @param string $ip_2 - ip alternativo
*
* @return array 
*/
function validar_ips(array $server, $ip_2) {

    #copio a array porque vai ser transformada
    $my_server = $server;

    #verifica de o ip é válido
    $ip1 = (filter_var($my_server['serverip'], FILTER_VALIDATE_IP)) ? $server['serverip'] : FALSE;

    #verifica se o ip é válido
    $ip2 = (filter_var($ip_2, FILTER_VALIDATE_IP)) ? $ip_2 : FALSE;

    $my_server['serverip'] = NULL;

    #se o ip1 não for válido então $my_server['serverip'] = ip2
    if (!$my_server['serverip'] = $ip1)
        $my_server['serverip'] = $ip2;

    #se nenhum dos ip for válido para a execução
    #aqui optei por filter_var para ter mesmo a certeza que tenho um ip válido
    if (!filter_var($my_server['serverip'], FILTER_VALIDATE_IP))
        return NULL;

    if (!$my_server = conexao_servidor($my_server))
        return FALSE;

    // retorno uma nova array para fazer a ligação ao servidor local
    return $my_server;
}

/**
* conexão á base de dados
*
*/
function conexao_servidor(array $server) {

    $n_server = $server;

    $db_host = $n_server['serverip'] . ":" . $n_server['db_porta'];

    //já faço a ligação ao servidor. Retorno false em vez do erro que ligação por questões de segurança
    if (!$n_server['conexao'] = mysql_connect($db_host, $my_server['db_user'], $my_server['db_password']))
        return FALSE;

    //defino a base de dados
    $n_server['database'] = mysql_select_db($n_server['db_name'], $n_server['conexao']);

    return $n_server;
}

//Se não conseguir conectar com um, conectar alternativo.
if (!validar_ips($server1, $s_ipserver11))
    if (!validar_ips($server2, $s_ipserver2))
       if (!validar_ips($server3, $s_ipserver33))
           echo "não foi possivel ligar";
    
12.09.2014 / 17:05