Jump to content

use variable connection strings without eval?


mottwsc

Recommended Posts

I have multiple servers and I'm trying to have a user connect to the right server based on their 'assigned' server.  So, I need to use different variable names based on that

 

in an include file earlier in the main script, I have...

$hostSignIn0001="server1";
$userSignIn0001="xxx1";
$passwordSignIn0001="yyy1";
$dbnameSignIn0001="zzz1";


$hostSignIn0001="server2";
$userSignIn0001="xxx2";
$passwordSignIn0001="yyy2";
$dbnameSignIn0001="zzz2";

 

in the main script, I have a variable that has the assigned server and I want to use the right connection variables based on this.  I could use eval to turn $hostSignIn into $hostSignIn0001 (and so forth for the other variables) and then it would pull the right info, but I'm looking for an alternative way to do this since I'd like to exclude eval from functioning in my scripts using php.ini.

 

Is there an alternative way to do this without using eval?

 

if (!$cxnSignIn = mysqli_connect($hostSignIn, $userSignIn, $passwordSignIn, $dbnameSignIn))
{ exit; }

 

Thanks.

 

You would either use an array or a switch/case statement.

 

You would never use eval() to determine values and variables to use. It is for when you need to evaluate php code that is in a string (such as for a template) and nothing you have shown in this post involves more than simple array indexing or simple conditional logic.

You could use one function and just have a ternary operator inside the function for each paramter and just switch them depending on the state of a constant; I have this method set, and apart from slight memory usage, and setting up a constant to use as a switch it functions fine, just a suggestion though ;)

 

Rw

are you try this

<?php
$hostSignIn0001="server1";
$userSignIn0001="xxx1";
$passwordSignIn0001="yyy1";
$dbnameSignIn0001="zzz1";


$hostSignIn0002="server2";
$userSignIn0002="xxx2";
$passwordSignIn0002="yyy2";
$dbnameSignIn0002="zzz2";

$site = 2;
$site = str_pad($site, 4, '0', STR_PAD_LEFT);
$host = ${'hostSignIn'.$site};
$user = ${'userSignIn'.$site};
echo "$host, $user";
?>

As PFMaBiSmAd suggested, I think an array would be better for something like this:

 

$cnxs = array(
    1 => array(
        'host' => 'server1',
        'user' => 'xxx1',
        'password' => 'yyy1',
        'dbname' => 'zzz1'
    ),
    2 => array(
        'host' => 'server2',
        'user' => 'xxx2',
        'password' => 'yyy2',
        'dbname' => 'zzz2'
    )
);

$site = 2;

if (!$cxnSignIn = mysqli_connect($cnxs[$site]['host'], $cnxs[$site]['user'], $cnxs[$site]['password'], $cnxs[$site]['dbname']))

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.