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

Asked

Viewed 1,051 times

0

I’m so sorry, but I had to rewrite my entire question because I wasn’t being objective enough to make myself understood, when I omit code as was the previous case is not to hide something is just to be able to understand what I respond to within my programming limitations, in any case as soon as the platform is ready I will make it available online.

In this first file the variables will be available so that they can be changed to make connections between the 3 servers the demonstration 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 following 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 do 4 includes on all the missing files I created the following.

#/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 by 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 connection to understand 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 connection 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;
?>

Connection to the local server

#/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 I have exposed and improved my doubt.

  • There is no break to if. It is not very clear what you want.

  • 1

    @Rjp, instead of writing comments, it’s better [Edit] the question to add details.

  • Yes it’s true you’re right @brasofilo

  • Yeah, because if someone else comes, you just have to read the question to understand the problem. There’s an explanation of you that’s down there in the answer, and it seems important...

  • @Rjp Server, I would like very much if you could solve your problem, but it is not clear what you want. You say you want to validate the ips because they may be wrong, and in Manuel Gerardo Pereira’s comment Voce says: "I know that the ips are valid that there is no doubt". Be clearer with the problem so we can help.

  • Reorganized and much more complete question.

Show 1 more comment

4 answers

8


I’m not sure that’s what you want. You need to know what kind are the $ip1 and $ip2 - if they are bool or if they are 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), will always return the last if due to overlap of the true conditions.

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

Option 3:

Solving overlap in case of two true 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 variable $ips with an array containing the $ip1 and $ip2 and then just use array_filter to filter all values that are null, and use will be zero $ips[0] - the first index containing 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;
}
  • The ips are real I mean either it’s my internal ip of my network or my external ip of my provider anyway do not know yet what is bool. Anyway I would like the ip selection to be automatic if one was wrong or if MYSQL could not connect.

  • 1

    See what guys are boolean. My #4 example automatically does what you want, test it and see the result.

  • Example #4 will work even if an ip is already out of date randomly?

  • It didn’t work @Papacharlie. I think with what I increased in the question I must have explained myself better.

  • I had not noticed!! Its update this excellent once again thank you very much.

  • 1

    Is a model for ip1, use it to ip2 and ip3. If you look, the structure is the same as mine example #3, just adapt. I was going to call you to chat, but your reputation is low... If it solves the problem mark the answer?

  • Marked and already changed in the question the merit and all its.

  • 1

    I’m glad you solved it. Always try to be as clear as possible when asking, and if you need to set an example of what you are doing, to avoid misinterpretation of the problem. :)

Show 3 more comments

0

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

a) In /folder/config.php all would-see are characteristics of a server then it is better to group them in an array. So we are sure that they 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) For the file /folder/connect/convention.php. The repeated code has been grouped into functions. I have as a rule, do not rely on the given parameters to be sure of the output of the function. Which is why, strange as it is, I checked the validity of the ips again. Here I give up performance and use more resources, to have consistency of output.

c) I did not understand well to connect to the first available server or if one of the three is not available connect to another server. As the case may be, I think this solution is suitable for both situations or more. With these functions tests the possibility of connecting to any server and can then 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";
  • Thanks for your interest @Manuel Gerardo Pereira but as the platform I’m developing is to make available online I will have to maintain a basic config and easy to set up as if I wanted to install because many people have no knowledge for themselves understand with an array such as me, I know and already said that a configuration with array will have to be an option in the future but it will have to be in a sub file, in relation to "b)" most of the scripts are executed by cron and as I intend to run some in very few seconds I cannot confirm the same thing 2 times.

  • In relation to "c)" in config there is the $Dbl variable which is what will tell the server itself who it is and will choose some situations in relation to db and always connect through its internal ip regardless of whether db is installed on the server itself or not or whether it is in convencao.php will always be available 4 ips, 2 of the internal server 1 itself that will always be used and another external that will never be used by itself and the external ips of the 2 other servers. In relation to debug thank you in the same.

  • After all what do you want to know? the value of the $Dbl variable? The ip of the internal server? Because it is not clear what is the expected result. If you want more performance you can take the validations

  • 1

    Nothing at this time the question of this question is answered and I have already changed in my question so that it works and thanks again for having shown me an alternative.

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 ());
  • I know that the ips are valid that there is no doubt now I can not touch the files that have the ips because they are updated by a synchronization system.

  • Here will not touch anything, just set a valid ip that will be saved in the variable $ip3 , then do what you want with this value. Between ip1 and or ip2 chose the one that is valid. Save this ip in a variable called $ip3, because it uses as understand.

  • see the response issue

  • Just a hint, before using a variable, always check that what is stored in it is what you expect. Here you are not absolutely sure that the synchronization system did not make any mistake in recording.

0

From what I understand you will receive the 2 Ips, but at a certain time IP 1, even if it is filled correctly will not answer the call mysql connection, so you should try to connect with IP 1 and in case of errors try on IP 2, I think something like this should serve:

<?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 worked well, the only detail is that if IP 1 is invalid, there is a delay until it passes to IP 2. See if it is not better to try IP 2 first and then pass to IP 1.

  • If you do the logical comparison instead of the loop, you might get faster : "if the ip1 connection didn’t work with ip2"

  • 2

    @Manuelgerardopereira How would it get faster, if the delay is due to the fact that mysqli keep trying to connect? loop or if da in the same... Maybe try to implement a smaller timeout, could not research about it, I leave to the OP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.