


Automated CSV and Excel Data Import to MySQL and PostgreSQL Databases Using PHP
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!

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

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

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

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]

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values and pointers to data rows, and is suitable for non-primary key column queries.

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

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