How can I connect to two databases - php

i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}

You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?

You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/

mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.

Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!

Related

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`');

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

Switch between multiple database in PDO

I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
I know that I am a couple of months late but you should be able to switch between databases from within your query.
examples:
$sql = "SELECT * FROM dbname.tablename";
$sql = "SELECT * FROM anotherdbname.anothertablename"
So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.
It looks like PDO does not have database switching because not every database engine supports it.
AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.
However if you're using mysql check if this works for you:
$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
$sql = 'select count(*) from table_name';
$res = $pdo->query($sql);
print_r($res->fetchAll());
$pdo->exec('USE db2');
$res = $pdo->query($sql);
print_r($res->fetchAll());
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
Edit: Interesting point by #laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
you don't even need to specify the database in every query, just use msyql syntax
USE db_name
and then write your requests
you can make this :
$database1 = new PDO("mysql:host=localhost;dbname=db1;charset=utf8;",$username, $password);
$database2 = new PDO("mysql:host=localhost;dbname=db2;charset=utf8;",$username, $password);
simple 😀

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.

Can you do queries against two databases if mysql_select_db was already used?

I have code that in the connection setup selects the database using mysql_select_db().
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db("database1");
Can I later run a query against two databases such as:
SELECT database1.row, database2.row
FROM database1.table, database2.table
WHERE database1.row = database2.otherrow
even though "database1" was already selected at first? Or is there a method for unselecting the database?
You can. Also check this out: How do I construct a cross database query in PHP?

Categories