使用 PHP 自动将 CSV 和 Excel 数据导入 MySQL 和 PostgreSQL 数据库

使用 PHP 自动将 CSV 和 Excel 数据导入 MySQL 和 PostgreSQL 数据库

数据库 2024-11-12 10:19:06 9个月前

要使用 php 自动将数据从 csv 或 excel 文件传输到 mysql 和 postgresql 数据库,请按照以下步骤操作:

先决条件

安装必要的库:

php 针对 mysql 和 postgresql 的 pdo 扩展。phpexcel 库(或 phpspreadsheet,如果可用,但我们将使用 phpexcel,因为它与 php 5.6 更兼容)。

下载 phpexcel 库并将其包含在您的项目目录中。


第 1 步:设置数据库连接

我们将使用 pdo 连接到 mysql 和 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());}?>

第 2 步:从 csv 或 excel 文件加载数据

我们将创建一个函数来读取 csv 或 excel 文件并将数据作为数组返回。

<?phprequire '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");    }}?>

第3步:将数据传输到mysql和postgresql

定义函数以将数据插入 mysql 和 postgresql。此示例假设数据是数组的数组,其中每个内部数组代表数据库中的一行。

<?phpfunction 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>";}?>

第四步:把它们放在一起

从文件中加载数据,然后将其传递给每个函数以插入到 mysql 和 postgresql 中。

<?php$filePath = 'path/to/yourfile.csv'; // or .xls / .xlsxtry {    $data = readFileData($filePath);    insertIntoMySQL($mysqlConnection, $data);    insertIntoPostgreSQL($pgConnection, $data);} catch (Exception $e) {    echo "Error: " . $e->getMessage();}?>

执行示例

确保 mysql 和 postgresql 数据库和表(your_mysql_table、your_pg_table)已设置并具有正确的列(column1、column2、column3)。将您的 csv 或 excel 文件放置在指定路径 ($filepath) 中。从命令行或浏览器(如果在 web 服务器上)运行此 php 脚本。

此脚本将从指定文件中读取数据并将其插入到两个数据库中。

立即学习“PHP免费学习笔记(深入)”;

与我联系:@ linkedin 并查看我的作品集。

请给我的 github 项目一颗星 ⭐️

文章版权声明:除非注明,否则均为网络转载文章,转载或复制请以超链接形式并注明出处。