use variable connection strings without eval?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mottwsc
Forum Commoner
Posts: 55
Joined: Sun Dec 23, 2007 8:01 pm

use variable connection strings without eval?

Post by mottwsc »

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...

Code: Select all

$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?

Code: Select all

if (!$cxnSignIn = mysqli_connect($hostSignIn, $userSignIn, $passwordSignIn, $dbnameSignIn))
{ exit; }
Thanks.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: use variable connection strings without eval?

Post by Jonah Bron »

Instead of a setup like you have,

Code: Select all

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


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

Code: Select all

$signIn = array(
    array(
        'host' => 'server1',
        'user' => 'xxx1',
        'password' => 'yyy1',
        'dbname' => 'zzz1'
    ),
    array(
        'host' => 'server2',
        'user' => 'xxx2',
        'password' => 'yyy2',
        'dbname' => 'zzz2'
    ),
Then just access the different login data like this:

Code: Select all

echo $signIn[0]['host']; //outputs 'server1'
mottwsc
Forum Commoner
Posts: 55
Joined: Sun Dec 23, 2007 8:01 pm

Re: use variable connection strings without eval?

Post by mottwsc »

Yep, it looks like an array will work here. Thanks for your suggestion.
Post Reply