


To automate data transfer from a CSV or Excel file to both a MySQL and PostgreSQL database using PHP, follow these steps:
Prerequisites
-
Install necessary libraries:
- PHP's PDO extension for MySQL and PostgreSQL.
- PHPExcel library (or PhpSpreadsheet if available, but we'll use PHPExcel as it's more compatible with PHP 5.6).
Download the PHPExcel library and include it in your project directory.
Step 1: Set Up Database Connections
We'll use PDO to connect to both MySQL and PostgreSQL.
<?php // MySQL connection $mysqlHost = 'localhost'; $mysqlDB = 'mysql_database'; $mysqlUser = 'mysql_user'; $mysqlPassword = 'mysql_password'; try { $mysqlConnection = new PDO("mysql:host=$mysqlHost;dbname=$mysqlDB", $mysqlUser, $mysqlPassword); $mysqlConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected to MySQL successfully.<br>"; } catch (PDOException $e) { die("MySQL connection failed: " . $e->getMessage()); } // PostgreSQL connection $pgHost = 'localhost'; $pgDB = 'pgsql_database'; $pgUser = 'pgsql_user'; $pgPassword = 'pgsql_password'; try { $pgConnection = new PDO("pgsql:host=$pgHost;dbname=$pgDB", $pgUser, $pgPassword); $pgConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected to PostgreSQL successfully.<br>"; } catch (PDOException $e) { die("PostgreSQL connection failed: " . $e->getMessage()); } ?>
Step 2: Load Data from CSV or Excel File
We will create a function that reads either a CSV or Excel file and returns the data as an array.
<?php require 'path/to/PHPExcel.php'; function readFileData($filePath) { $fileType = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); if ($fileType === 'csv') { $data = []; if (($handle = fopen($filePath, 'r')) !== false) { while (($row = fgetcsv($handle, 1000, ',')) !== false) { $data[] = $row; } fclose($handle); } return $data; } elseif ($fileType === 'xls' || $fileType === 'xlsx') { $data = []; $excel = PHPExcel_IOFactory::load($filePath); $sheet = $excel->getActiveSheet(); foreach ($sheet->getRowIterator() as $row) { $rowData = []; $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); foreach ($cellIterator as $cell) { $rowData[] = $cell->getValue(); } $data[] = $rowData; } return $data; } else { throw new Exception("Unsupported file format"); } } ?>
Step 3: Transfer Data to MySQL and PostgreSQL
Define functions to insert data into both MySQL and PostgreSQL. This example assumes the data is an array of arrays, where each inner array represents a row in the database.
<?php function insertIntoMySQL($mysqlConnection, $data) { $query = "INSERT INTO your_mysql_table (column1, column2, column3) VALUES (?, ?, ?)"; $stmt = $mysqlConnection->prepare($query); foreach ($data as $row) { $stmt->execute($row); } echo "Data inserted into MySQL successfully.<br>"; } function insertIntoPostgreSQL($pgConnection, $data) { $query = "INSERT INTO your_pg_table (column1, column2, column3) VALUES (?, ?, ?)"; $stmt = $pgConnection->prepare($query); foreach ($data as $row) { $stmt->execute($row); } echo "Data inserted into PostgreSQL successfully.<br>"; } ?>
Step 4: Putting It All Together
Load data from the file, then pass it to each function to insert into both MySQL and PostgreSQL.
<?php $filePath = 'path/to/yourfile.csv'; // or .xls / .xlsx try { $data = readFileData($filePath); insertIntoMySQL($mysqlConnection, $data); insertIntoPostgreSQL($pgConnection, $data); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>
Example Execution
- Make sure the MySQL and PostgreSQL databases and tables (your_mysql_table, your_pg_table) are set up and have the correct columns (column1, column2, column3).
- Place your CSV or Excel file in the specified path ($filePath).
- Run this PHP script from the command line or a browser (if on a web server).
This script will read the data from the specified file and insert it into both databases.
Connect with me:@ LinkedIn and checkout my Portfolio.
Please give my GitHub Projects a star ⭐️
The above is the detailed content of Automated CSV and Excel Data Import to MySQL and PostgreSQL Databases Using PHP. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

Article discusses securing MySQL against SQL injection and brute-force attacks using prepared statements, input validation, and strong password policies.(159 characters)


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.