开发者

Is It Possible to Select a MySQL Connection String Based on the Value of a Variable?

开发者 https://www.devze.com 2023-03-12 11:23 出处:网络
I would like to connect to different databases depending on the value of a variable. I was thinking of trying something like this:

I would like to connect to different databases depending on the value of a variable.

I was thinking of trying something like this:

if ($city = 'phoenix') {
   mysql_connect("x", "y", "z") or die(mysql_error());
   mysql_select_db("databasename") or die(mysql_error());
}

if ($city = 'losangeles') {
   mysql_connect("a", "b", "c") or die(mysql_error());
   mysql_select_db("databasename2") or 开发者_JAVA技巧die(mysql_error());
}

Is this possible?


As Tomalak said, yes.

Though, consider a switch statement.

switch ($city) {
    case 'phoenix':
        //do db
        break;
    case 'losangeles':
        //do db
        break;
    default:
        //do db
}


Yes.

Yes, it is.

Give it a go!

(Though watch your syntax for conditionals. = is assignment; == is comparison.)


Yes, certainly possible. But it does open up another level of error possibilities and headaches for the person maintaining it. My company's main app was written this way, and it's a nightmare. That being said, it is possible to conditionally set the DB.

Or you could just use fully qualified values (use dbname.tablename)

0

精彩评论

暂无评论...
验证码 换一张
取 消