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)
精彩评论