Insert in two php database mysql [closed]

1

I want to insert data from one database into two databases at the same time using PHP / MYSQL.

Is there a possibility? .

I'm just getting through a connection, when I make the require of two connections nothing happens!

I need a code example for friends

    
asked by anonymous 15.10.2016 / 22:59

1 answer

3

If it's on the same server:

$con = mysqli_connect( 'end.do.servidor', 'usuario', 'senha ' );

if( !$con ) die( 'Falha na conexao: '.mysqli_connect_error( $con ) );

$sql1 = 'INSERT INTO nomedobanco1.tabela1 (....)';
$sql2 = 'INSERT INTO nomedobanco2.tabela2 (....)';

if( mysqli_query( $con, $sql1 ) ) echo 'Inserção 1 OK' else die( mysqli_error( $con ) ); 
if( mysqli_query( $con, $sql2 ) ) echo 'Inserção 2 OK' else die( mysqli_error( $con ) ); 

If they are different servers:

$con1 = mysqli_connect( 'end.do.servidor1', 'usuario', 'senha ' );
$con2 = mysqli_connect( 'end.do.servidor2', 'usuario', 'senha ' );

if( !$con1 ) die( 'Falha na conexao 1: '.mysqli_connect_error( $con1 ) );
if( !$con2 ) die( 'Falha na conexao 2: '.mysqli_connect_error( $con2 ) );

$sql1 = 'INSERT INTO nomedobanco1.tabela1 (....)';
$sql2 = 'INSERT INTO nomedobanco2.tabela2 (....)';

if( mysqli_query( $con1, $sql1 ) ) echo 'Inserção 1 OK' else die( mysqli_error($con1 ) );
if( mysqli_query( $con2, $sql2 ) ) echo 'Inserção 2 OK' else die( mysqli_error($con2 ) );

For PDO, the logic is the same, just adapt the syntax.

If you are using a single connection, and an engine as InnoDB, you can use BEGIN TRANSACTION before% 2 INSERT if COMMIT then to ensure that the transaction is only if all goes well in both inserts, avoiding that only one table is modified. If you are using two connections, you need to think of another solution to ensure consistency.

    
15.10.2016 / 23:16