Multiple Databases and Transactions

If I use two databases, should I start a transaction? Is this correct, or is this code incorrect? If I make a mistake in the second request, then call rollback (), but unfortunately the first request will not be rolled back ...

 $conn_site=mysql_connect("localhost", "us", "ps");
 mysql_select_db("site",$conn_site); 
 $conn_forum=mysql_connect("localhost", "us", "ps");
 mysql_select_db("forum",$conn_forum); 

     function begin() {

         @mysql_query("BEGIN",$conn_site);
         @mysql_query("BEGIN",$conn_forum);
     }
    function commit_reg() {
        @mysql_query("COMMIT",$conn_site);
        @mysql_query("COMMIT",$conn_forum);
    }
    function rollback(){
        @mysql_query("ROLLBACK",$conn_site);
        @mysql_query("ROLLBACK",$conn_forum);
    }
   begin();
    mysql_query("insert into users (....) or rollback();
       mysql_query("insert into forumusers (....) or rollback();
    commit();
+3
source share
3 answers

It will not crouch. Transactions are isolated within the same "database." For transactions to span multiple databases, you need what is called "distributed transaction management." Standards for this include the XTA. More enterprise-oriented frameworks, including Java J2EE, include standards such as the standard.

, PHP, , . , Mysql ( ). , db , ... . - , .

+5

mysql XA, , ​​ , . PHP XA, .

+11

What you really have to do is use one database connection to use both databases.

In MySQL, a “database” is really more like a “directory” or “schema” on other servers. You can use tables from another database in the same connection as permissions.

+1
source

Source: https://habr.com/ru/post/1732246/


All Articles