How can MySQL replication be utilized to synchronize databases in PHP applications?
MySQL replication can be utilized in PHP applications to synchronize databases by setting up a master-slave configuration. The master database serves as the primary database that receives all the write operations, while the slave database replicates these changes to maintain synchronization. This setup ensures that any changes made to the master database are automatically propagated to the slave database, allowing for redundancy and improved performance.
// Connect to the master database
$master = new mysqli('master_host', 'username', 'password', 'database');
// Connect to the slave database
$slave = new mysqli('slave_host', 'username', 'password', 'database');
// Perform write operations on the master database
$master->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Query the slave database to retrieve synchronized data
$result = $slave->query("SELECT * FROM table_name");
while ($row = $result->fetch_assoc()) {
// Process synchronized data
echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
// Close database connections
$master->close();
$slave->close();