MYSQL connect and query 2 dbs on 2 different server - php

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

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.:)

php MySQL error for retrieving data

I have a PHP code for selecting data from a database, but it produces NULL result, although the same query performed manually works well. Here's relevant part of code:
$conn = mysqli_connect($host,$user,$password);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_db_name($dbName,$conn);
$query = "SELECT Images.Path,p.NameAr,p.DescriptionAr FROM
(SELECT * FROM project where TypeID = 1) as p
JOIN Images where Images.ProjectID = p.ID";
$result = mysql_query($query,$conn);
var_dump($result);
What can be wrong about it?
Not sure about PHP related error but your query formation is not corect.
Change your query like below. Moreover, you are not fetching any column from images table then why do a join with images table?
SELECT Path,NameAr,DescriptionAr
FROM
(
SELECT p.* FROM project p
JOIN
Images i on i.ProjectID = p.ID and p.TypeID = 1
) tab
You use mysqli_connect but then you wrote mysql_* If you fix all mysql_* to mysqli_* it should work.

mulitiple database select php mysql

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.

How to use avg function?

I'm new at php and mysql stuff and i'm trying to use an avg function but i don't know how to.
I'm trying to do something like this:
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die ("Did not connect to $database");
mysql_query("AVG(column1) FROM table1 ") or die(mysql_error());
mysql_close();
echo AVG(column1);
(Q1)I'd like to see the value printed in the screen, but i'm getting nothing but an error message. How could I print this average on the screen ?
(Q2)If I had a column month in my table1, how could I print the averages by the months ?
Sorry for any bad English, and thanks for the attention.
Solution for Q1: SELECT AVG(column1) FROM table1
Solution for Q2: SELECT AVG(column1), month FROM table1 GROUP BY month
What to read?
MySQL SELECT syntax
MySQL AVG() function - there is even an example of exactly what you need
PHP mysql_fetch_assoc() function which is one of several ways to retrieve data from result set
btw: PDO is much better for database communication in PHP
Ad. 1:
$sql = 'SELECT AVG(col_name_1) AS avgColName FROM tbl_name;';
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
var_dump($result['avgColName']);
Ad. 2:
SELECT ... FROM ... GROUP BY MONTH(date_col_name);
You need to return the result of the query into a variable which you can then use.
For example:
$query = "AVG(column1) FROM table1";
$result = mysql_query($query);
// Print out result
while($row = mysql_fetch_array($result)) {
echo $row['AVG(column1)'];
}

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