How do I migrate data from another database to MySQL

Migrating data from another database to MySQL can be done in several ways, depending on the source of the data. Below, you'll find a simple example of how to do this using PHP and the MySQLi extension. This example assumes you are transferring data from a PostgreSQL database to a MySQL database.

Example Code

<?php // Source PostgreSQL Database Credentials $pg_host = "your_pg_host"; $pg_db = "your_pg_database"; $pg_user = "your_pg_user"; $pg_pass = "your_pg_password"; // Target MySQL Database Credentials $mysql_host = "your_mysql_host"; $mysql_db = "your_mysql_database"; $mysql_user = "your_mysql_user"; $mysql_pass = "your_mysql_password"; // Connect to PostgreSQL Database $pg_conn = pg_connect("host=$pg_host dbname=$pg_db user=$pg_user password=$pg_pass"); if (!$pg_conn) { die("Could not connect to PostgreSQL: " . pg_last_error()); } // Connect to MySQL Database $mysql_conn = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_db); if ($mysql_conn->connect_error) { die("Connection failed: " . $mysql_conn->connect_error); } // Query data from PostgreSQL $result = pg_query($pg_conn, "SELECT * FROM your_table"); if (!$result) { die("Error in query: " . pg_last_error()); } // Insert data into MySQL while ($row = pg_fetch_assoc($result)) { $sql = "INSERT INTO your_mysql_table (column1, column2) VALUES ('". $row['column1'] ."', '". $row['column2'] ."')"; if (!$mysql_conn->query($sql)) { echo "Error: " . $mysql_conn->error; } } // Close connections pg_close($pg_conn); $mysql_conn->close(); ?>

Keywords: migrate data MySQL PostgreSQL database migration PHP