mulitiple database select php mysql - php

I have 2 databases on the same server with 2 identical tables.
What I want to do is select all records from both tables and join them in one array.
I've been messing around with the script below. For some reason it returns the records of db2.tbl twice and doesn't return the db1.tbl records at all. When I try to select the data from a single database is works fine for both of them. Does any one see the problem?
<?PHP
require_once("config.php");
$conn = #mysql_connect($dbhost, $dbuser, $dbpass)or die ('Error connecting to mysql server'.mysql_error());
$q = mysql_query("SELECT * FROM db1.tbl JOIN db2.tbl");
var_dump(mysql_num_rows($q));
while($arr = mysql_fetch_assoc($q)){
var_dump($arr);
}
?>

Is this what you want ? All records from database1 followed by all records from database2:
$q = mysql_query("SELECT * FROM db1.tbl UNION SELECT * FROM db2.tbl");
I assume the user you are connecting with has access to both databases.

Your query should work. However add tilt(`) to your database name table name. Execute the query first in mysql see whether it is ok than execute with php.

Related

How to implement a mysql query that performs inner join from two different database in PHP using mysqli_query?

I've been using PHP mysqli functions since long but never came accross such a senario where I need to join two tables from different database.
Suppose I've table t1 from database d1 & table t2 from database d2 with a common column say id.
I am stuck here:
mysqli_select_db($conn1,"d1") or die("Error selecting database");
$conn2 = mysqli_connect("localhost","root","") or die("Error connecting Database");
mysqli_select_db($conn2,"d2") or die("Error selecting database");
$sql = "SELECT * from d1.t1 tab1 inner join d2.t2 tab2 on tab1.id = tab2.id";
$result = mysqli_query(**don't know**,$sql);
$row = mysqli_fetch_array($result);
Please tell me what should I write in place of "don't know". Also suggest any better way, if any to get this done.
Thanks in advance.:)

CodeIgniter multiple database query

I tried to run query on multiple database with following sql query:
// Collect clients db name
$dbs = array();
foreach($cafes as $cafe)
{
$dbs[] = $cafe->db_name; // client_7
}
// Run multi database query
foreach($dbs as $db)
{
$this->db->select("$db.orders.*,(select count($db.order_items.id) from $db.order_items where $db.order_items.siparis_id = orders.id) as urun_sayisi, (select sum($db.order_items.tutari) from $db.order_items where $db.order_items.siparis_id = orders.id) as price");
}
$this->db->get()->result();
In above example, i have cafe clients and each client have own db named ex: client_7. I am trying to do list all client orders. I got following error with above query:
Unknown table 'client_7' in field list
How can list all rows on orders table from multiple database?
Please mention database name ahead your table name..
for example
SELECT userid FROM db1.user;
SELECT userid FROM db2.user;
Try this:
<?php
$secound_db= $this->load->database('database_two', TRUE);
$query = $secound_db->get('person');
var_dump($query);
Source

MYSQL connect and query 2 dbs on 2 different server

MYSQL connect and query 2 dbs on 2 different server
THANKS in advance for any help,
I've been trying for a week to get this to work,
and have googled various examples on this site and on others.
i'm trying to connect 2 db, on the same server.
i can get data from each seperatly, but i don't know how to wrire code to combine / join the data
this is my incorrect code based on numerous help and
how to post i've read online. ANY help or clues are welcome.
If i can just get anything to output / print i would be happy
// connect to db1 contact info
$host1='db1hostname';
$user1='db1user';
$password1='db1pw';
$database1='db1user';
// connect to db2, phone call info
$host2='db2hostname';
$user2='db2user';
$password2='db2pw';
$database2='db2user';
$connect1 = mysql_connect($host1, $user1, $password1) OR DIE
('Unable to connect to database! Please try again later.');
$connect2 = mysql_connect($host2, $user2, $password2) OR DIE
('Unable to connect to database! Please try again later.');
// i think this is where things start to go wrong
mysql_select_db($database1, $connect1);
mysql_select_db($database2, $connect2);
// i want to join these 2 tables from diff db by the caller info
which is a cell number
// the database 2 info comes from a phone call records table
and can't be altered, so i can't connect the 2 tbls by the table primary id
because i never know what the id will be for each call in db2,
i wish to connect the 2 db tables by caller cell number
$data = mysql_query("SELECT `m`.`id`, `m`.`created`, `m`.`caller`, `m`.`content_text`,
`c`.`iname`, `c`.`caller`
FROM database1.contacts c, database2.messages m
WHERE `c`.`caller` = `m`.`caller` ") or die(mysql_error());
// i then want to print the results to a table
while($info = mysql_fetch_array( $data ))
Connect to your first database and when you want to run a query in the second database just use the simple way like in below code.
$query = "SELECT t1.*, t2.*
FROM tableOfDB1 t1
LEFT JOIN database2.tableOfDB2 t2 ON t1.ID = ts2.TableOne_ID
";
Or if you want data only from db2
$query = "SELECT t2.*
FROM database2.tableOfDB2 t2";
In your example try this
$data = mysql_query("SELECT `m`.`id` AS mID, `m`.`created` AS mCreated, `m`.`caller` AS mCaller, `m`.`content_text`,
`c`.`iname` AS cIname, `c`.`caller` AS cCaller
FROM database1.contacts c, database2.messages m
WHERE `c`.`caller` = `m`.`caller` ") or die(mysql_error());
while( $row = mysql_fetch_array($data) )
{
echo "<br>mCaller: ".$row['mCaller'];
echo "<br>cCaller: ".$row['cCaller'];
}
If, as you say, the databases are on the same server, then you can do everything with one connection. You have to be explicit about your database names in your queries, but then you can do everything else in a very straightforward way.
See https://stackoverflow.com/questions/19039718/reference-column-in-seperate-database/19040228#19040228

php how to insert query result from server 1 to server 2 table in mySQL php

I'm new to PHP first of all ..
My question is once I got the $result from Server1 using mysql_query , how can I create Table2 that would stored in host2
<?php
$connect1 = mysql_connect(host1,user,pass);
$selected = mysql_select_db(database1,$connect1);
$result = mysql_query("select a,b,c from table1");
$connect2 = mysql_connect(host2,user,pass);
$selected = mysql_select_db(database2,$connect2);
mysql_query("create table table2 as select $result from table2");
?>
They are two different servers (both in MySQL) .. answer in details would appreciated.
Thanks
mysql_query accepts two parameters. The second is the connection, have you tried this?
mysql_query("create table table2 as select $result from table2", $connect2);
PHP Documentation on mysql_query:
http://php.net/manual/en/function.mysql-query.php

How to connect to 2 databases at the same time in PHP

I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.
At the moment the only way I've figured out is to connect to both databases with a different user for each.
I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results.
Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.
Any other ideas?
You'll need to pass a boolean true as the optional fourth argument to mysql_connect(). See PHP's mysql_connect() documentation for more info.
If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example:
SELECT column
FROM database.table
Depending on what you need to do, you might be able to do an INSERT INTO and save a bunch of processing time.
INSERT INTO database1.table (column)
SELECT database2.table.column
FROM database2.table
Lucas is correct. I assume that both the databases are hosted on the same host.
Alternatively, you can create only 1 db connection and keep swapping the databases as required. Here is pseudo code.
$db_conn = connect_db(host, user, pwd);
mysql_select_db('existing_db', $db_conn);
-- do selects and scrub data --
mysql_select_db('new_db', $db_conn);
-- insert the required data --
I would suggest using two connection handlers
$old = mysql_connect('old.database.com', 'user', 'pass);
mysql_select_db('old_db', $old);
$new = mysql_connect('new.database.com','user','pass);
mysql_select_db('new_db', $new)
// run select query on $old
// run matching insert query on $new
If it's an option, use PDO: you can have as many database connections open as you like.
Plus, assuming your executing the same queries over and over, you can use prepared statements.
You can easily use 2 databases in same time with following Codes:
<?php
define('HOST', "YOURHOSTNAME");
define('USER', "YOURHOSTNAME");
define('PASS', "YOURHOSTNAME");
define('DATABASE1', "NAMEOFDATABASE1");
define('DATABASE2', "NAMEOFDATABASE2");
$DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);
$DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);
if(!$DATABASE1){
die("DATABASE1 CONNECTION ERROR: ".mysqli_connect_error());
}
if(!$DATABASE2){
die("DATABASE2 CONNECTION ERROR: ".mysqli_connect_error());
}
$sql = "SELECT * FROM TABLE"; /* You can use your own query */
$DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);
$DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);
$DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);
$DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);
/* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */
echo $DATABASE1_RESULT['id'];
echo $DATABASE2_RESULT['id'];
/*After complete your all work don't forgot about close database connections*/
mysqli_close($DATABASE1);
mysqli_close($DATABASE2);
?>
First Connect Two Database
$database1 = mysql_connect("localhost","root","password");
$database2 = mysql_connect("localhost","root","password");
Now Select The Database
$database1_select = mysql_select_db("db_name_1") or die("Can't Connect To Database",$database1);
$database_select = mysql_select_db("db_name_2") or die("Can't Connect To Database",$database2);
Now if we want to run query then specify database Name at the end like,
$select = mysql_query("SELECT * FROM table_name",$database1);

Categories