create different mysql connection and choose

PHP coding talk.

Moderator: Moderators

create different mysql connection and choose

Postby roders22 on Wed Feb 28, 2007 3:11 pm

Hi all,
Is it possible for me to create different mysql connection in a config.php file and then when choose one of when in different pages. Like for e.g in my config.php file i'll have
mysql_connect('localhost','user','pass');
mysql_select_db('db');

mysql_connect('localhost1','user1','pass1');
mysql_select_db('db1');

So in page1.php i'll choose the connection with locahost and in page2.php i'll choose the connection with localhost2.
Is this possible? Or is there a way to work around this?
User avatar
roders22
Registered User
Registered User
 
Posts: 141
Joined: Thu Jun 09, 2005 4:33 pm
Location: Mauritius

Postby PostBot on Wed Feb 28, 2007 6:16 pm

In your pages use something like this:
Code: Select all
<?php
define('DB_ITEM', 'host1');
include('config.php');
...
?>
then in config.php use code like this:
Code: Select all
<?php

$databases = array(
'host1' => 'localhost,user,pass,dbname1',
'host2' => 'localhost,user2,pass2,dbname2',
);
$item = explode(',', defined('DB_ITEM') ? $databases[DB_ITEM] : $databases['host1']);

$db = mysql_connect($item[0], $item[1], $item[2]);
if($db === false)
{
  die('Cannot connect: ' . mysql_error());
}
if(!mysql_select_db($item[3]))
{
  die('Cannot use database: ' . mysql_error());
}

?>
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars

Postby roders22 on Thu Mar 01, 2007 9:24 am

Hi tried it,
Can you tell what this line does?
Code: Select all
$item = explode(',', defined('DB_ITEM') ? $databases[DB_ITEM] : $databases['host1']);

Am not sure what to do with this. It only selecting the first connection all the time.
User avatar
roders22
Registered User
Registered User
 
Posts: 141
Joined: Thu Jun 09, 2005 4:33 pm
Location: Mauritius

Postby PostBot on Thu Mar 01, 2007 9:56 am

It checks if constant "DB_ITEM" is defined, if it is defined then uses connection defined in that variable, otherwise it uses first connection. explode() splits connection string to host/user/password/database array.
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars

Postby roders22 on Thu Mar 01, 2007 10:48 am

Thx for the explanation. Got it working now.
User avatar
roders22
Registered User
Registered User
 
Posts: 141
Joined: Thu Jun 09, 2005 4:33 pm
Location: Mauritius


Return to PHP Programming

Who is online

Users browsing this forum: No registered users and 1 guest