I am trying to use PHP and MySQL's Create Table Select between two different MySQL servers. I am not sure this can be done like this with SQL. I get no errors but I get nothing done either:
<?php
$dbname = 'cms';
$dbmaster = 'cmsms';
$db1 = mysql_connect('localhost', 'root', 'secret');
if (!$db1) {
echo 'Could not connect to mysql';
exit;
}
$db2 = mysql_connect('server2', 'root', 'secret');
if (!$db2) {
echo 'Could not connect to mysql';
exit;
}
mysql_select_db("$dbname", $db1) or die ("Unable to select database");
mysql_select_db("$dbmaster", $db2) or die ("Unable to select database");
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql, $db1);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
$sql = "DROP TABLE `$row[0]`";
mysql_query($sql, $db1);
echo "Table rows: {$row[0]} Deleted <br/>";
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
mysql_query($sql, $db1);
echo "Table: {$row[0]} created <br/>";
}
echo "<br/>done...";
mysql_free_result($result);
?>
That line:
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
just doesn't work. the $db2 doesn't make it go to the other server and select.
From doing some reading on SO I found someone similar and someone said it could not be done and to look at federated tables, which will not work for me.
If this cannot be done above does anyone know a way to do what I am doing? I am dropping the tables on the copy and re-creating them based on the table in the master. Then I am selecting the data in the master to put in the re-created tables. Thank you
Update:
Just so I can be clear. The code works if everything were on the same server and I only had one database connection. It is because of the create table select that I have problems, I believe. This SQL needs to use two servers at the same time. The create table is for one database that just dropped it's tables but the select is selecting from the database of the second connection - two connections in the same SQL statement.
Yes, on your PHP script you can perform all queries you want on all different servers you have access and permission to.
You don't specify your database on the $sql though. You specify it when you run the mysql_query function.
So, your code:
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql, $db1);
Is wrong. It should only be:
$sql = "SHOW TABLES";
$result = mysql_query($sql, $db1);
By using $db1 on the second parameter of mysql_query you are already specifying that you want to show tables from that database only.
Following the same reasoning on the other sentences, you should be able to get results you want.
You won't be able to do this:
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
If you want to insert rows from $db2 into newly created tables into $db1, you need to:
Run a query on $db2 to get results
Create table on $db1
Iterate $db2 results
Insert records on new table on $db1
There is no magic way of doing this in only one sentence.
You're on the right track but missing an important point. Your PHP code has opened a connection to db1 and db2 but that doesn't mean that the db1 server knows about the db2 server. Therefore you can't pass db1 a query with db2 in it and expect it to get rows from it. Your PHP script has to act as an intermediary.
You need to issue a select statement to select rows from db1's table, then loop over the results issuing insert statements for db2. Of course you do this after you issue a create table statement to create the blank table. I'm also assuming you're trying the 'create table select from' trick because you don't know how to issue the create table to copy the layout of the table in db1. Have you seen this?
http://dev.mysql.com/doc/refman/5.0/en/show-create-table.html
remove the $db2 database connection from your query
If you want to run SQL on $db1 use this
mysql_query($sql, $db1);
If you want to run SQL on $db2 use this
mysql_query($sql, $db2);
I don't think this is the best database design Johnny, depends of course on what you're trying to achieve. If you simply want to store data on both servers for redundancy, you should go with MySQL Replication. If you're separating data for high availability purposes, then consider data sharding, partitioning and definitely take a look at MySQL Proxy.
These will let you do all the work outside your application, so you wouldn't have to alter your application in case your sharding/partitioning/backup/redundancy scheme changes. Such tools make this completely invisible to your application.
Sorry if this is off-topic.
There are a few choices you have in regards to setting this up.
1) Implement mysql asynchronous replication. This would do the same thing you are trying to do in PHP but would be much more efficient.
Mysql Documentation: Replication
2) Fix your script to stream data from master server to backup server.
This would be done by creating the table and then loading the result row by row into the backup server's table.
Related
First of all sorry for my English.
Im trying to delete / insert some rows to a MSSQL Table but i get no error but it just doesnt work. But when I do a SELECT statement it works as well.
$dbhandle = mssql_connect("SERVERNAME", "username", "password") or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db("myDB", $dbhandle) or die("Couldn't open database $myDB");
mssql_query("DELETE dbo.import");
The server SQL INSTANCE is installed on my local computer and I'm the Administrator of this SQL Server but the Webserver is on another PC.
I created the user and I assigned the role db_owner
When I try the same query on another SQL Server, it works.
I also tryed:
$dbhandle = mssql_connect("SERVERNAME", "username", "password") or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db("myDB", $dbhandle) or die("Couldn't open database $myDB");
$result = mssql_query("DELETE dbo.import; SELECT * FROM dbo.import;");
$sqlRows = array();
while($row = mssql_fetch_array($result))
{
$sqlRows[] = $row;
}
echo sizeof($sqlRows);
and the echo return 0, but when I check from SSMS the records are still there.
DELETE SCHEMA.TABLE; SELECT * FROM SCHEMA.TABLE;
returns 0 rows. And then I try again
SELECT * FROM dbo.import;
returns 26 rows.
Ok I just found the answer searching on the Web.
There was a rollback as mentioned from Shnugo and adding SET IMPLICIT_TRANSACTIONS OFF; at the beginning of the query it solve the problem.
Thank you
EDIT 2
The solution was a not committed transaction. See comments...
EDIT
My answer is not right to the point... I must admit, that I never used DELETE without FROM, but this works obviously:
create table #tbl(id int);
insert into #tbl values(1),(2);
select * from #tbl;
delete #tbl;
select * from #tbl;
drop table #tbl;
I let the answer there due to the comments...
I am trying to send database table from one server to another database table in different server. Here is the PHP code I have tried so far, but to no avail:
<?php
$dblink1=mysql_connect('server', 'user', 'pass'); // connect server 1
mysql_select_db('db1_name',$dblink1); // select database 1
$dblink1=mysql_connect('server', 'user', 'pass'); // connect server 2
mysql_select_db('db2_name',$dblink2); // select database 2
$table='output_table';#not sure if this is correct
$tableinfo = mysql_fetch_array(mysql_query("SHOW CREATE TABLE first_table ",$dblink1)); // get structure from table on server 1
echo $tableinfo;
mysql_query(" $tableinfo[1] ",$dblink2); // use found structure to make table on server 2
$result = mysql_query("SELECT * FROM first_table ",$dblink1); // select all content
while ($row = mysql_fetch_array($result, MYSQL_ASSOC) ) {
mysql_query("INSERT INTO output_table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')",$dblink2); // insert one row into new table
}
mysql_close($dblink1);
mysql_close($dblink2);
echo "complete";
?>
I have tried the output_table with and without the same column names/amount as first_table, but it does not seem to be working.
Again, any help would be appreciated.
The problem might be that $dblink2 is undefined.
$dblink2=mysql_connect('server', 'user', 'pass'); // connect server 2
mysql_select_db('db2_name',$dblink2); // select database 2
Also consider using pdo methods instead because mysql- methods are now less favored to the PDO way of working with database objects.
This is most likely a firewall issue. Most 3rd party hosts don't allow you to access MySQL from 'the outside'.
You can do this if you manage the MySQL server yourself or if you have a host that doesn't deny you to access the database from another machine, but in regular web hosting, this is not common.
o to your phpMyAdmin installation and look for the file config.inc.php. Open that file, and check which hostname / ip is being used
I am using the external authentication system. Therefore, there are a lot of user data, which is not available in Phorum.
I am using the last post module, although I want to get the information from the last post user, from my own user table (I have some data, like avatar, birth info etc). I want to show in my Phorum. How can I achieve this?
I've tried to simply connect via a: mysql_query(); but then I just get No database selected error.
I've searched for hours - I cannot find any documentation regarding getting custom data from your own user table.
I would recommend using mysqli, as mysql is deprecated. First make sure that your connection is correct. No database selected means you probably do not have your connection included at the top.
$con = mysqli_connect("localhost","username","password","database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error());
}
Make sure that your sql statement looks like so (Notice the $con in the mysqli_query()):
$sql = "select * from TableName";
if ($que = mysqli_query($con, $sql)) {
// Query has ran
}
Hello guys i have problem with inserting data in mysql database.I accepted a project that my friend worked.
I make simple php test file and try to insert in table _content_city. query is successfully executed bu no records in database column when i check in phpmyadmin.
$handler = mysql_connect($server, $user, $pass);
$database = mysql_select_db($dbname);
if(!$handler) :
die("Faild connect to MySQL :" . mysql_error());
endif;
if(!$database) :
die("DB with name ". $dbname . " no exists " . mysql_error());
endif;
mysql_query("INSERT INTO _content_grad (wishlist) VALUES('BlaBlaBla') ") or die(mysql_error());
printf ("Inserterd records: %d\n", mysql_affected_rows());
When i execute this code in browser i have message Inserterd records: 1
But when i check in phpmyadmin that data no exist in column. I dont know whay.
You guys can see image and u will see column wishlist is empty.
http://img710.imageshack.us/img710/1852/5hfw.png
I check foreign_keys and remove all foreign_keys and again dont work.
Like test i make new database with name new_test_base and make table albums and column title and like test i execute my php code and all data is successfully inserted when i check in phpmyadmin. So problem is only in that database, i have full access and privilegies i use root (ALL)
Any solution to fix this. Thanks
The MySQL_* range of functions have been depreciated and are no longer reccomened for use. Use the MySQLi_* range of functions instead.
In your code, put the following line echo mysql_errno($handler) and it should display the latest error retuned by MySQL, a MySQLi version of this function is also available.
I'm trying to delete a row from a table in MySQL using the PHP code below. The return value from mysql_affected_rows() is 1. There are no errors. However, the row still exits in MySQL. Not sure what I'm doing wrong. Any thoughts?
$db = array('host'=>'127.0.0.1',
'user'=>'root',
'pass'=>'',
'name'=>'testdb');
// CONNECT TO THE MYSQL SERVER
$connection = mysql_connect($db['host'], $db['user'], $db['pass']);
if(!$connection){
// HANDLE ERROR HERE
die('Unable to connect to MySql server : '.mysql_error($connection));
}
// SELECT THE DATABASE SCHEMA
if(!mysql_select_db($db['name'],$connection)){
// HANDLE ERRORS HERE
die('Unable to connect to database : '.mysql_error($connection));
}
$result = mysql_query("delete from photos where id=".$photo_id, $connection);
echo mysql_affected_rows($connection);
UPDATE
I added the following code to the end and that solved the issue -
mysql_query("commit", $connection);
Thanks for the comments!
Applied to innodb tables as in your case.
mysql_query("BEGIN", $connection);
// delete code
mysql_query("COMMIT", $connection);
What I typically do in this cases is to enable the general_log (set global general_log_file=general.log; and set global general_log=1;) and look what arrives in there.
Then it often becomes already obvious what is the problem.
If it is not clear yet what is going on you can run these queries on the mysql console...