How to store form data in 2 different databases?

Asked

Viewed 122 times

5

I have a form that data needs to be saved in a local bank and another database on a server.

Is there any way to do that without duplicating the "Insert" code? In the connection file I configured the 2 connections, but only inserts in the localhost.

    $host = '***';
    $user= '***';
    $pass = '***';
    $db= '***';
    $con=mysqli_connect($host, $user, $pass, $db);

    $host2='localhost';
    $user2='***';
    $pass2='***';
    $con2=mysqli_connect($host2, $user2, $pass2, $db);
  • Some error appears in the $con2 ?

  • 1

    You can also set up a replication between banks. So you work with only one bank and the changes will be reflected to the other automatically.

  • @Rray doesn’t seem any mistake

  • @Earendul in this case, this is not feasible.

2 answers

5


The only way I see it is like this:

$insert = "INSERT INTO TABELA (CAMPO_1, CAMPO_2) VALUES (VALOR_1, VALOR_2)";
mysqli_query($con, $insert);
mysqli_query($con2, $insert);
  • 2

    Thanks!! I hadn’t thought of it that way!

5

class databaseConfig{

    var $default = array(
        'host'          => '127.0.0.1',
        'login'         => 'root',
        'password'      => '',
        'database'      => 'local',
    );

    var $server = array(
        'host'          => '192.168.100.101',
        'login'         => 'root',
        'password'      => '',
        'database'      => 'server',
    );
}

class SimpleMySqlConnect{

    private $config = array();
    private $connections = array();

    function __construct(){
        if(class_exists("databaseConfig")){
            $this->config = new databaseConfig();
        }

        $connections = get_object_vars($_this->config);
        foreach($connections as $name => $config){
            $this->connections[$name] = new mysqli($config['host'], $config['login'], $config['password'], $config['database']);
        }
    }

    function getConnection($name){
        if(in_array($name, $this->connections)){
            return $this->connections[$name];
        }
    }

    function getConnections(){
        return $this->connections;
    }
}

...

$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$simpleMySql = new SimpleMySqlConnect();
$connections = $simpleMySql->getConnections();
foreach ($connections as $name => $mySqlClass){

    $stmt = $mySqlClass->prepare($query);
    $stmt->bind_param("sss", $val1, $val2, $val3);

    $val1 = 'Stuttgart';
    $val2 = 'DEU';
    $val3 = 'Baden-Wuerttemberg';

    $stmt->execute();
}

...

Reference

PHP

Obs

I could not test, I do not have Mysql on this computer, if anyone finds any error and want to adjust. Please do it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.