How to connect to multiple databases in a single PHP page? [duplicate] - php

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How do you connect to multiple MySQL databases on a single webpage?
If I want to connect to one db do some query, and then later do another query from another DB. How do I do it? Do I just
mysql_pconnect("host:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test") or die(mysql_error());
//do some query
mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test") or die(mysql_error());
//do another query
Is that how you do it? A couple of questions. Notice I used pconnect, does that affect calling it twice on the same page? Also, do I have to close the connection for the first one before calling the second one?

You need to store database connection link in separate variable. For example
$connection_1 = mysql_connect("host:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test", $connection_1) or die(mysql_error());
$connection_2 = mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test", $connection_2) or die(mysql_error());
mysql_query("your query", $connection_1); // run query for first connection
mysql_query("your query", $connection_2); // run query for second connection

You need to store the resource returned from mysql_connect and use it when doing mysql_select_db.
$res1 = mysql_pconnect(...);
mysql_select_db("Test", $res1);
$res2 = mysql_pconnect(...);
mysql_select_db("Test", $res2);
Then use $res1 or $res2 when querying the corresponding db.
mysql_query("select * from test_table", $res1);
mysql_query("select * from test_table", $res2);

Is that how you do it?
This will leave your script with two open connections to different hosts until it ends.
You may reuse either of these connections by calling mysql_pconnect again.
Notice I used pconnect, does that affect calling it twice on the same page?
From the docs:
The function would first try to find a (persistent) link that's already open with the same host, username and password
Since your hosts are different, there will be two different connections
Also, do I have to close the connection for the first one before calling the second one?
You cannot explicitly close a connection open with mysql_pconnect.

You did RTM, right, because you're not using the $link_identifier?
http://us.php.net/mysql_select_db :
bool mysql_select_db ( string $database_name [, resource $link_identifier ] )
Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.
Parameters
database_name
The name of the database that is to be selected.
link_identifier The MySQL connection.
If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Whenever you have use the pconnect, you're sharing the connection (not only within the page, but possibly with other pages) -- in your case here, don't do that. You want isolated links, therefore isolated transactions. You should probably consider mysql_connect instead, and explicitly using the new_link parameter. Lastly, use the $link_identifier explicitly, so you are clear what you are connecting to.

Related

Can we use this simple method instead of using variable itself

I have marked many of developers using
$con1 = mysql_connect('localhost', 'username', 'password');
$rv1 = mysql_select_db('db1'); // not added connection
Instead
$con1 = mysql_connect('localhost', 'username', 'password');
$rv1 = mysql_select_db('db1', $con1); // added connection
Can I know the difference between this both?
Actually this both are giving same result
The mysql_ functions will implicitly use the last connection which was opened with mysql_connect, if you do not pass an explicit connection parameter. So, yes, in this case it's the same result whether you pass the parameter or not. You will get different results should you happen to open more than one connection using mysql_connect.
Note that implicitly relying on an open connection is bad practice, precisely because your application will screw up if you need to open more connections sometime later. Also note that the mysql_ API is dead, switch to mysqli or PDO.
Take a look at the PHP manual:
http://www.php.net/manual/en/function.mysql-select-db.php
Without a link identifier, mysql_select_db will use the last connection opened with mysql_connect or it will try to connect without any parameter. So the second one is safer and you could use multiple connections.
mysql_select_db and mysql_connect is deprecated though. You should switch to PDO or mysqli.
Taken from the documentation:
bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Basically it will used the last known connection object if none is provided. In your case, the last known connection was created on the previous line. This is an optional parameter so the function will operate in the same way if the connection is passed explicitly or not.
On a related note, please notice the big red warning at the top of the documentation page I have linked to. The mysql_* extensions are deprecated and it is recommended that you use a different extension. For a more detailed explanation, please take a look at this thread:
Why shouldn't I use mysql_* functions in PHP?

accessing two mysql databases from one php file

this is what i currently do:
i create 2 connections:
$con_1 = mysql_connect('xxxxxxxx', 'db1', 'xxxxx') or die(mysql_error());
$con_2 = mysql_connect('xxxxxxxx', 'db2', 'xxxxx') or die(mysql_error());
the before each query, i do
mysql_select_db('db1', $con_1);
... query
but apparently that doesn't work. mysql_query requires me to pass in the $con_1 as well. so If I have to pass in the connection, may i skip the step of calling mysql_select_db all together?
OR, can I just call each mysql_select_db in the beginning and later when I call the query functions, just pass in the $con_x, and not have to worry about selecting the db?
The database selection is associated with the connection resource. So you can select it once for each connection.
If you don't call mysql_select_db at all, all your queries will need to specify explicit database prefixes before all the tables, e.g. select * from db1.table ....
so If I have to pass in the connection, may i skip the step of calling mysql_select_db all together?
You'll have to call it once after establishing the connection
But, like #Barmar mentioned in his answer, you wont even need to call mysql_select_db() and and you don't need to have two seperate connections for that. You'll just have to use fully qualified table names in your queries, like dbname.tablename. Check this example:
$con = mysql_connect(...);
mysql_query('SELECT * FROM `db1`.`foo`');
mysql_query('SELECT * FROM `db2`.`bar`');

resource in mysql_connect in php

I am trying to connect to database through php.I did it lots of time. But I want to know how many rows exist in my table.
I've tried to use php manual, however, I was confused.
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
The above code worked on :
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
But when I decided to use
$link = mysql_connect("localhost", "mysql_user", "mysql_password","database");
It occurred an error like this:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
What is difference between codes? And how can I solve it?
Thanks in advance
The 4th parameter to mysql_connect is supposed to be a boolean type indicating whether you always want a new connection (even if mysql_connect was called earlier), not a string. As a result, $link is false because mysql_connect failed.
PHP documentation on mysql_connect
selecting DB as 4th parameter in mysql_connect is wrong - the functions returns false and no mysql_num_rows() following is possible
The mysql_connect function accept 5 arguments. In that in 4th argument this should be either true or false. But you have passed the string. This is not correct. you cann't pass the database name here.
For more tutorial see here and also this link.
You can not select database by mysql_connect() function. This function is used to connect to the database, not to query the database. To query the database use mysql_select() instead.
this parameters are allowed in mysql_connect
mysql_connect(server,user,pwd,newlink,clientflag)
please check http://www.w3schools.com/php/func_mysql_connect.asp

mysqli escape string additional parameter

Why mysqli_real_escape_string is asking additional parameter? In procedural method we must include connection establishment also. Whats logic behind that?
You're providing database connection link. This is so that you could have multiple MySQL connections at once.
In certain scenarios, you may want to open several connections and connect to multiple MySQL databases. Explicitly stating the connection link identifier that you want to use allows you to query multiple MySQL databases without worrying about conflicts.
//Open connections to two separate databases. For example: DatabaseOne and DatabaseTwo
$databaseOne = mysqli_connect("example.com", "user", "password", "DatabaseOne");
$databaseTwo = mysqli_connect("example.com", "user", "password", "DatabaseTwo");
//Make variable clean for first connection to DatabaseOne
$var= mysqli_real_escape_string($databaseOne, $var);
//QUERY TABLE FROM DATABASE ONE
$res1 = mysqli_query($databaseOne, "SELECT col FROM tableInDatabaseOne WHERE col = '$var'");
//do something with $res1
//QUERY TABLE FROM DATABASE TWO
$res2 = mysqli_query($databaseTwo, "SELECT col FROM tableInDatabaseTwo");
//do something with $res2

How to connect multiple database,servers in mysql and query from both tables of each other?

I am looking forward to connect two different database from different servers. Also, i would want to run a query that fetches data from both the database into a single result. Am doing this in PHP script with mysql. here is how am looking forward to do it [ without success :) ]
$dbh1 = mysql_connect('server1', 'uname', 'pwd')or die("Unable to connect to MySQL1");
$dbh2 = mysql_connect('server2', 'uname', 'pwd') or die("Unable to connect to MySQL2");
mysql_select_db('db1', $dbh1);
mysql_select_db('db2', $dbh2); //both will have same table name though
$qry = mysql_query("select * from db1.table1 where db1.table1.id='100' and db1.table1.id=db2.table1.id",$dbh1) or die(mysql_error());
$row= mysql_fetch_array($qry);
echo $row[2];
Am not getting any result or either error. Any help is appreciated, tnx.
According to the PHP docs:
http://il2.php.net/manual/en/function.mysql-query.php
"If the link identifier is not specified, the last link opened by mysql_connect() is assumed."
So in this case you're only retrieving data from $dbh2.
I don't think it's possible to do what you are trying to do with one query. You should merge the results after you get them.
It doesn't work that way. You can use multiple databases in a single SQL query, but it always operates on one connection handle. If you need to connect to two different servers, you have to use two queries and merge data in PHP.

Categories