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);
Related
I'm trying to update table rows to have random numbers. Now I can achieve this using phpMyAdmin and run it via SQL query. However if I try and run the same code via a PHP call then it doesn't work.
Any ideas why this would be the case and how I would correct it?
Table name is: num_image
Column Name: rownum
This is the SQL I'm using:
SET #rownum := 0;
UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND();
I've tried entering it in my php code as follows:
<?php
// Connect to database
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// Assigns a new random number with no duplicates to database for each rownum row.
$updaterownum = mysql_query("SET #rownum := 0; UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND();");
echo 'All rownums have been updated!';
?>
My database connection works fine as I use the same for other database updates and inserts. So I've narrowed it down to how I'm inserting the actual SQL in my PHP call and believe I have to edit the way I call it?
I'm sure it's something minor I have missed, though I'm stumped. Thanks in advance!
I see a document at:
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Here are some brief lines:
MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.
Multiple statements or multi queries must be executed with mysqli_multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.
The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.
The following polished code can do the job in PHP. However, as mentioned in comments; The mysql extension is deprecated and will be removed in the future.
<?php
// Connect to database
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if($con)
{
$updaterownum = mysql_query("SET #rownum := 0");
$updaterownum = mysql_query("UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND()");
if(mysql_affected_rows()>0)
{
echo 'All rownums have been updated!';
}
else
{
echo "Nothing changed after running update query!";
}
}
else
{
echo "Not able to connect";
}
?>
$Link= mysql_connect("localhost", "root", "", "");
query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='$val'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query($Link,"INSERT INTO table_name(col_name)VALUES('$val')"); )
}
There will be multiple calls to query at same time. I used this method to avoid multiple insertion, but sometimes multiple rows are inserted.Please help me. Thanks in advance.
thanks for your help..
I m not calling this code in loop but multiple calls at same time from different users are made.
mysql_query syntax: resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
$query1 = mysql_query("INSERT INTO table_name (col_name)VALUES('".$val."')");
Full code:
$Link= mysql_connect("localhost", "root", "", "");
$query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='".$val."'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query("INSERT INTO table_name(col_name)VALUES('".$val."')");
}
If there are multiple simultaneous requests to the web server(s) that host the PHP, the select could return no results for more than one of these requests, and then there may be multiple inserts due to each such request performing the insert.
If you are not running windows and have only one web server, you could synchronize access to this code using PHP's semaphores.
But even better, can you put a unique constraint on the value of this column in the table in mysql?
Though your code is correct and it should not insert again, but
You should add a unique key to your field and then use Insert Ignore
"INSERT IGNORE INTO table_name(col_name)VALUES('$val')"
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
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.
I've tried to find the answer to this question but none of the answers fit.
I have two databases, one has 15.000.000 entries and I want to extract the necessary data and store it in a much smaller database with around 33.000 entries. Both databases are open at the same time. Or at least they should be.
While having the big database open and extracting the entries from it, is it possible to check whether the value already exists in a certain table in the smaller database? I just need some generic way which checks that.
In my code I'm first opening both databases (big one is oddsnavi_push, small one is oddsnavi_baby):
$database = "oddsnavi_push";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$database_baby = "oddsnavi_baby";
$db_handle_baby = mysql_connect($server, $user_name, $password);
$db_found_baby = mysql_select_db($database_baby, $db_handle_baby);
And then I'm starting to read and calculate data from oddsnavi_push:
$SQL_SELECT_ALL = "...giant query...";
$result_select_all = mysql_query( $SQL_SELECT_ALL );
while($db_field_all = mysql_fetch_assoc( $result_select_all ) ) {
$SQL_INSERT="INSERT INTO oddsnavi_baby.calc (id, one, two) VALUES ('$id', '$one', '$two')";
It works up until that point. It takes the data which was read (id, one, two) and inserts them in proper columns in oddsnavi_baby table named calc. It does that properly when the oddsnavi_baby is completely empty.
However, I need it to only update the database IF an entry (based on whether a certain 'id' exists or not) doesn't exist.
EDIT: I will rephrase my question. From the query results (big database) I'm getting strings, for every row. For example $string. How do I open the second database and check if oddsnavi_baby.calc table has the $string value in column Events?
Skip the check and try with just INSERT IGNORE assuming the Id is a unique key.
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Man, I remember coming up against a problem like this once. I think we actually went the slow, expensive route and wrote a script to pull one entry at a time, compare it, and insert it if it didn't already exist.
However, I found this post, which sounds like it might be of some help to you:
http://www.mysqlfaqs.net/mysql-faqs/Tricky-Select-Queries/How-to-compare-data-of-two-tables-of-two-different-databases-in-MySQL
Good luck :)
Why do you really need multiple database? Amount does not matter tables are just fine, no need to split.
//Multiple links to different databases
$dblink1 = mysqli_connect($localhost, $user, $pass, $db1);
$dblink2 = mysqli_connect($localhost, $user, $pass, $db2);
$id = '1'; // Id to check
$query = "SELECT COUNT(*) FROM `table` WHERE id = '1' LIMIT 1";
$result = mysqli_query($dblink1, $query); //query db 1
if(mysql_num_rows($result)) {
$query = "INSERT INTO `table` VALUES(.....)";
$result = mysqli_query($dblink1, $query); //query db 2
}