$hosts = array ('10.0.0.6', '10.0.0.4', '10.0.0.5');
$rand_keys = array_rand($hosts);
$sqlh = mysql_connect($hosts[$rand_keys[0]], 'username', 'password');

guys, i am trying to write a script that will randomly pick a server. but if a server is down, it just dies.. how can i make it that if the server fails, it trys one of the other servers?

thanks

    revising my connect script.. still need it to do the rollover if a server is down.

    srand((float) microtime() * 10000000);
    $input = array ("10.0.0.4", "10.0.0.5", "10.0.0.6");
    $rand_keys = array_rand($input,2);
    //echo $input[$rand_keys[0]] . "\n";
    if ($input[$rand_keys[0]] == '10.0.0.4')
    {
    echo"You are using server 1";
    }
    else
    if ($input[$rand_keys[0]] == '10.0.0.6')
    {
    echo"You are using server 2";
    }
    else
    if ($input[$rand_keys[0]] == '10.0.0.5')
    {
    echo"You are using server 3";
    }
    $sqlh = @mysql_connect($input[$rand_keys[0]], 'USERNAME', 'PASSWORD');
    if (!$sqlh) {
    die('Not connected : ' . mysql_error());
    }
    $db_selected = @mysql_select_db('DATABASE', $sqlh);
    if (!$db_selected) {
    die ('Can\'t use DATABASE : ' . mysql_error());
    }

    //if we aren't connected, wrap it up
    if (!$sqlh) {
    require_once('header.php');
    echo '<br><span class="special">Database is down</span><br>';
    require('footer.php');
    die();
    }

      Would it be reasonable in this situation to just do a connect and then a small select statement, and if the select returns an empty value, disconnect and try the next server?

      Of course this select would need to be based on data you know exists on every single database for sure.

        yes, all 3 servers are identical.. how would this work though?

        i do want it to be random on which server they use.

        thanks

          You could do it like this:

          $servernum=rand(1,3);
          
          $server1=$ip1;
          $server2=$ip2;
          $server3=$ip3;
          
          $server='$server' . $servernum;
          

          I don't know if that works exactly for assigning a variable to another variable, I haven't tried it, but that's what I would look into trying first.

          Then do your MySQL select based on the value $server, and check a value to see if it's empty.

          Hope this gives you some ideas.

            Originally posted by sysera
            I don't know if that works exactly for assigning a variable to another variable, I haven't tried it, but that's what I would look into trying first.

            $server .= $servernum;

              Originally posted by Kudose

              $server .= $servernum;

              [/B]

              Thank you Kudose. 🙂

                Write a Reply...