How to link two mysql databases in two different machines? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a mysql database called 'sample1' on one of my windows laptops and another mysql database called 'sample2' in the other machine. I want to connect both these machines together first and link the databases 'sample1' and 'sample2' so that the query I execute in 'sample1' must be reflected in 'sample2' also (distributed query processing).
Eg: if sample1 and sample2 contain 5 records, by deleting a record in sample1 must be reflected in sample2 also.
I use WAMP and work on PHP alongside MySQL. Kindly help...

As I understand, You need that sample1 is identical to sample2 and that automaticly the queries are distributed.
It looks like the best way (maybe not the easiest) is to use the replication of mysql : https://dev.mysql.com/doc/refman/5.0/en/replication-howto.html
EDIT : this answer may not be the answer that you need because with replication you will need that 1 of the two server (The master server) stay up everytime or you will need a third server if you want to shutdown the two other.

The following code opens two MySQL server connections ($conn1 and $conn2) and then each connection will select one database to use.
$database1 = "students";
$database2 = "employees";
$conn1 = mysql_connect('host1', 'user', 'password');
if(!$conn1) {
die("Not connected: ". mysql_error());
}else{
mysql_select_db($database1, $conn1);
}
$conn2 = mysql_connect('host2', 'user', 'password', TRUE);
if(!$conn2) {
die("Not connected: ". mysql_error());
}else{
mysql_select_db($database2, $conn2);
}

There have 2 solutions for your reference.
Mysql maser-slave mode(mysql replication),in your case we assume 'sample1' as master , other database('sample2') as slave , when you delete data from foo table of sample1 , this operation will reflect the foo table of 'sample2'.More details please see https://www.digitalocean.com/community/tutorials/how-to-set-up-master-slave-replication-in-mysql
Mysql FEDERATED Storage Engine , this engine will mapping remote data to local,the effect same as item 1 .
please see the link:
https://dev.mysql.com/doc/refman/5.1/en/federated-storage-engine.html]
Hope this can help you!

You can follow this article in order to do a database replication or follow the steps bellow.
You have here a tutorial written by Falko Timme that will show how to replicate the database exampledb from the master with the IP address 192.168.0.100 to a slave. Both systems (master and slave) are running Debian Sarge; however, the configuration should apply to almost all distributions with little or no modification.
To configure the master we first have to edit /etc/mysql/my.cnf. We have to enable networking for MySQL, and MySQL should listen on all IP addresses, therefore we comment out these lines (if existant):
#skip-networking
#bind-address = 127.0.0.1
Furthermore we have to tell MySQL for which database it should write logs (these logs are used by the slave to see what has changed on the master), which log file it should use, and we have to specify that this MySQL server is the master. We want to replicate the database exampledb, so we put the following lines into /etc/mysql/my.cnf:
log-bin = /var/log/mysql/mysql-bin.log
binlog-do-db=exampledb
server-id=1
Then we restart MySQL:
/etc/init.d/mysql restart
Then we log into the MySQL database as root and create a user with replication privileges:
mysql -u root -p
Enter password:
Now we are on the MySQL shell.
GRANT REPLICATION SLAVE ON *.* TO 'slave_user'#'%' IDENTIFIED BY '<some_password>'; (Replace <some_password> with a real password!)
FLUSH PRIVILEGES;
Next (still on the MySQL shell) do this:
USE exampledb;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
The last command will show something like this:
+---------------+----------+--------------+------------------+
| File | Position | Binlog_do_db | Binlog_ignore_db |
+---------------+----------+--------------+------------------+
| mysql-bin.006 | 183 | exampledb | |
+---------------+----------+--------------+------------------+
1 row in set (0.00 sec)
Write down this information, we will need it later on the slave!
Then leave the MySQL shell:
quit;
There are two possibilities to get the existing tables and data from exampledb from the master to the slave. The first one is to make a database dump, the second one is to use the LOAD DATA FROM MASTER; command on the slave. The latter has the disadvantage the the database on the master will be locked during this operation, so if you have a large database on a high-traffic production system, this is not what you want, and I recommend to follow the first method in this case. However, the latter method is very fast, so I will describe both here.
If you want to follow the first method, then do this:
mysqldump -u root -p<password> --opt exampledb > exampledb.sql (Replace <password> with the real password for the MySQL user root! Important: There is no space between -p and <password>!)
This will create an SQL dump of exampledb in the file exampledb.sql. Transfer this file to your slave server!
If you want to go the LOAD DATA FROM MASTER; way then there is nothing you must do right now.
Finally we have to unlock the tables in exampledb:
mysql -u root -p
Enter password:
UNLOCK TABLES;
quit;

Related

ERROR importing SQL Database in PHP Admin [duplicate]

Error
SQL query:
--
-- Database: `work`
--
-- --------------------------------------------------------
--
-- Table structure for table `administrators`
--
CREATE TABLE IF NOT EXISTS `administrators` (
`user_id` varchar( 30 ) NOT NULL ,
`password` varchar( 30 ) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;
MySQL said:
#1046 - No database selected
need some help here.
You need to tell MySQL which database to use:
USE database_name;
before you create a table.
In case the database does not exist, you need to create it as:
CREATE DATABASE database_name;
followed by:
USE database_name;
You can also tell MySQL what database to use (if you have it created already):
mysql -u example_user -p --database=example < ./example.sql
I faced the same error when I tried to import a database created from before. Here is what I did to fix this issue:
1- Create new database
2- Use it by use command
3- Try again
This works for me.
If you're trying to do this via the command line...
If you're trying to run the CREATE TABLE statement from the command line interface, you need to specify the database you're working in before executing the query:
USE your_database;
Here's the documentation.
If you're trying to do this via MySQL Workbench...
...you need to select the appropriate database/catalog in the drop down menu found above the :Object Browser: tab. You can specify the default schema/database/catalog for the connection - click the "Manage Connections" options under the SQL Development heading of the Workbench splash screen.
Addendum
This all assumes there's a database you want to create the table inside of - if not, you need to create the database before anything else:
CREATE DATABASE your_database;
If you are doing this through phpMyAdmin:
I'm assuming you already Created a new MySQL Database on Live Site (by live site I mean the company your hosting with (in my case Bluehost)).
Go to phpMyAdmin on live site - log in to the database you just created.
Now IMPORTANT! Before clicking the "import" option on the top bar, select your database on the left side of the page (grey bar, on the top has PHP Myadmin written, below it two options:information_schema and name of database you just logged into.
once you click the database you just created/logged into it will show you that database and then click the import option.
That did the trick for me. Really hope that helps
For MySQL Workbench
Select database from Schemas tab by right mouse clicking.
Set database as Default Schema
Edit your SQL file using Notepad or Notepad++
add the following 2 line:
CREATE DATABASE NAME;
USE NAME;
Assuming you are using the command line:
1. Find Database
show databases;
2. Select a database from the list
e.g. USE classicmodels; and you should be off to the races! (Obviously, you'll have to use the correctly named database in your list.
Why is this error occurring?
Mysql requires you to select the particular database you are working on. I presume it is a design decision they made: it avoids a lot of potential problems: e.g. it is entirely possible, for you to use the same table names across multiple databases e.g. a users table. In order to avoid these types of issues, they probably thought: "let's make users select the database they want".
If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!
be careful about blank passwords
mysqldump [options] -p '' --databases database_name
will ask for a password and complain with mysqldump: Got error: 1046: "No database selected" when selecting the database
the problem is that the -p option requires that there be no space between -p and the password.
mysqldump [options] -p'' --databases database_name
solved the problem (quotes are not needed anymore).
Check you have created the database first which you want.
If you have not created the dataBase you have to fire this query:
CREATE DATABASE data_base_name
If you have already created the database then you can simply fire this query and you will be able to create table on your database:
CREATE TABLE `data_base_name`.`table_name` (
_id int not null,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (_id)
);
Solution with an Example
Error 1046 occurs when we miss to connect our table with a database. In this case, we don't have any database and that’s why at first we will create a new database and then will instruct to use that database for the created table.
# At first you have to create Database
CREATE DATABASE student_sql;
# Next, specify the database to use
USE student_sql;
# Demo: create a table
CREATE TABLE student_table(
student_id INT PRIMARY KEY,
name VARCHAR(20),
major VARCHAR(20)
);
# Describe the table
describe student_table;
quoting ivan n :
"If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!"
These are the steps:
Create a Database, for instance my_db1, utf8_general_ci.
Then click to go inside this database.
Then click "import", and select the database: my_db1.sql
That should be all.
first select database : USE db_name
then creat table:CREATE TABLE tb_name
(
id int,
name varchar(255),
salary int,
city varchar(255)
);
this for mysql 5.5 version syntax
I'm late i think :] soory,
If you are here like me searching for the solution when this error occurs with mysqldump instead of mysql, try this solution that i found on a german website out there by chance, so i wanted to share with homeless people who got headaches like me.
So the problem occurs because the lack -databases parameter before the database name
So your command must look like this:
mysqldump -pdbpass -udbuser --databases dbname
Another cause of the problem in my case was that i'm developping on local and the root user doesn't have a password, so in this case you must use --password= instead of -pdbpass, so my final command was:
mysqldump -udbuser --password= --databases dbname
Link to the complete thread (in German) : https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/
In Amazon RDS, merely writing use my-favorite-database does not work if that database's name includes dashes. Furthermore, none of the following work, either:
use "my-favorite-database"
use `my-favorite-database`
use 'my-favorite-database'
Just click the "Change Database" button, select the desired database, and voilà.
Although this is a pretty old thread, I just found something out. I created a new database, then added a user, and finally went to use phpMyAdmin to upload the .sql file. total failure. The system doesn't recognize which DB I'm aiming at...
When I start fresh WITHOUT first attaching a new user, and then perform the same phpMyAdmin import, it works fine.
Just wanted to add: If you create a database in mySQL on a live site, then go into PHPMyAdmin and the database isn't showing up - logout of cPanel then log back in, open PHPMyAdmin, and it should be there now.
For an added element of safety, when working with multiple DBs in the same script you can specify the DB in the query, e.g. "create table my_awesome_db.really_cool_table...".
jst create a new DB in mysql.Select that new DB.(if you r using mysql phpmyadmin now on the top it'l be like 'Server:...* >> Database ).Now go to import tab select file.Import!

MySQL cannot select a row inserted in a different session

My question is in the title.
I open a MySQL session in an application, and that application calls a script that creates another session. I insert a record in that new session, but when I select in the previous session, I cannot see the inserted row.
The following is the insert query:
INSERT INTO VCS.project_files (track_nbr, path, filename)
VALUES ('$track_nbr', '$path', '$filename');
The following is the select:
SELECT pf.project_file_id, pf.track_nbr, pf.filename, pf.path, pf.status
FROM VCS.project_files pf;
I found out this was due to isolation level set to 'repeatable reads'. 'Repeatable reads' means exactly what it says, each read in the old session will get the exact same rows.
In order to fix this, I had to set the database to 'read committed' by doing the following:
Adding the following lines to /etc/my.cnf (Ubuntu) /etc/my.cnf.d/my.cnf (CentOS):
[mysqld]
binlog_format = row
transaction-isolation = READ-COMMITTED
Restarting MySQL (in Ubuntu):
sudo service mysql restart
This allows all sessions to see committed changes from other sessions.
I was used to Oracle database ('read committed' by default) and MySQL is different ('repeatable reads' by default).

How to retrieve data from multiple host database table in php and mysql

We have a two database connection, which is given below,
$link1 = mysqli_connect($host1,$user1,$pass1,$db1);
$link2 = mysqli_connect($host2,$user2,$pass2,$db2);
Here, Host and Database are remote.
$query = "SELECT db1_tbl1.name as name,db1_tbl1.email as email ,db2_tbl2.address
as address FROM db1.table1 as db1_tbl1 INNER JOIN db2.tble2 as db2_tbl2 ON
db1_tbl1.std_id = db2_tbl2.std_id WHERE program_id = '$program_id' LIMIT 1,10";
mysqli_query($link1,$query);
If i use $link1 in mysqli_query, the error is showing
SELECT command denied to user 'user_name'#'remote_host_ip' for table 'table_name'
For First Link($link1)
If i use $link2,
SELECT command denied to user 'user_name'#'remote_host_ip' for table 'table_name'
For Second Link($link2)
Normally, separately two remote database connection and retrieving data is ok(it works perfectly)
But the problem is showing when i would like to retrieve data to join two remote host database.
Actually, How can i get data from the query which two connection will work at same time.
How to set the two database connection link in mysqli_query
Pleas any help?
You can use FEDERATED storage engine in MySQL.
At First , You have to enable FEDERATED storage engine.
You have to go my.ini file in MySQL and open it.
Comment it the #skip-federated instead of skip-federated.
The word "federated" copy to paste after [mysqld] like below
[mysqld]
federated
A table create in your local server same as your remote server table and add connection in last
CREATE TABLE federated_table (
....
.........(same as your remote server table)
)
ENGINE=FEDERATED
DEFAULT CHARSET=latin1
CONNECTION='mysql://fed_user#remote_host:9306/federated/test_table';
since your two table is remote host, you can create two federated table.
I hope that You can do your work perfectly.
You can visit it.
http://dev.mysql.com/doc/refman/5.1/en/federated-create-connection.html
It is possible to do this using the FEDERATED storage engine in MySQL.
The FEDERATED storage engine lets you set up a table on one of the servers that contains no data - it pulls the data from the other server. In your SQL queries, you treat it like a normal table, so you can do joins, select from it, insert, delete, etc.
But the FEDERATED storage engine is not enabled by default.
You would need to be able to restart the Mysql server binary with the --federated flag.
Basically, you would need to have root shell access (ssh) to do this, which means it is probably not a real solution if your databases are on a shared host.
Other options are:
Copy the data from one database to another (eg. a temporary table) and then do the join.
Select all of the data from both tables into the application and then perform the join in the application.

No result found/Result found

i'm new in asking questions here in the site, here is the situation:
Im using a Xampp Control Panel,
I have two systems, the old one and the new one (the new one is just the upgraded version of the old one).
I have 2 databases, let's name it db1 and db2, (db1 is the dbase used for the old one, and db2 is the dbase used for the new one.)
both databases have the same tables and contents except for one table, in db1.tb_final_dtr the structure has only 10 columns while db2.tb_final_dtr has 11 columns though the 10 columns in each table is the same with each other, and also both tables have the same records.
-I tried to queried both database with simple query lets say "SELECT * FROM tb_final_dtr WHERE hr_id = 'ASM12-0101'", the problem is, db1 shown 10 records right away, while db2 shown empty result. They both have the same table structure and records, they just differ in database name and the number of columns in one table.
WHAT SEEMS TO BE THE PROBLEM? hope you can reply at my question right away. Thanks a lot.
Your DB_2 is not working on NEW system..
Go to PHPmyadmin (on your NEW system) and add new user with username & password written from your conf file (and server name as localhost) of your website :P
So
go to PMA
add new user
enter data (server, username, password)
reload mysql
Of course, DB name in config file may also be wrong if tables are duplicated who knows what so check that too.
Good luck!

2300 request to mysql using php takes 2 hours , how to optimize

am working on a news paper project but without Rss Feed, so i was Compelled to make it's feed programatically using php , so i have 2300 process of processing pages and inserting in Mysql the results of the processing ,
so the technique i used is to process every single page and then insert it's contents in mysql , it's working good but some times i got "MySQL server gone" ,
i tried to process 30 page and insert them in one request but it stop's after some time
so i am asking about any way to optimize this processing to reduce the time used in ?!
thanks alot
Your batch insert approach is correct and likely to help. You need to find out why it stops after some time like you say.
It is likely the php script timing out. Look for max_execution_time on your php.ini file to make sure it's high enough to allow for the script to finish.
Also, make sure your mysql config allows for a large enough packet because you're sending large batches which may be large.
Hope that helps!
There are plenties of reasons why "MySQL server has gone away". Take a look.
Anyway, it is strange that you load the WHOLE pages. Usually RSS feed implies that you put there just a subject and some text snippet. I'd create RSS feed as simple XML file so it is not necessary to load data from MySQL on EVERY hit users do. You create news -> regenerate RSS XML file, you wrote new article -> regenerate RSS XML file.
If you still want to prepare your data to be inserted, just create a file with ALL inserts and then load data from this file.
$ mysql -u root
mysql> \. /tmp/data_to_load.sql
Yes! all 2300 at a time ;)
$generated_sql = 'insert into Table (c1,c1,c3) values (data1,data2,data3);insert into Table (c1,c1,c3) values (data4,data5,data6);';
$sql_file = '/tmp/somefile';
$fp = fopen($sql_file, 'w');
fwrite($fp, $generated_sql, strlen($generated_sql)); // wrote sql script
fclose($fp);
`mysql -u $mysql_username --password=$mysql_password < $sql_file`;
Backticks are necessary in the last line!
$ mysql -u root test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 171
Server version: 5.1.37-1ubuntu5.5 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create table test (id int(11) unsigned not null primary key);
Query OK, 0 rows affected (0.12 sec)
mysql> exit
Bye
$ echo 'insert into test.test values (1); insert into test.test values (2);' > file
$ php -a
Interactive shell
php > `mysql -u root < /home/nemoden/file`;
php > exit
$ mysql -u root test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 180
Server version: 5.1.37-1ubuntu5.5 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select * from test
-> ;
+----+
| id |
+----+
| 1 |
| 2 |
+----+
2 rows in set (0.00 sec)
So, as you can see, it worked perfectly.

Categories