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

DDD
发布: 2024-11-12 09:03:20
转载
1169人浏览过

使用 php 自动将 csv 和 excel 数据导入 mysql 和 postgresql 数据库

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

先决条件

  1. 安装必要的库:

    • php 针对 mysql 和 postgresql 的 pdo 扩展。
    • phpexcel 库(或 phpspreadsheet,如果可用,但我们将使用 phpexcel,因为它与 php 5.6 更兼容)。
  2. 下载 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 文件并将数据作为数组返回。

<?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");
    }
}
?>
登录后复制

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

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

<?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>";
}
?>
登录后复制

第四步:把它们放在一起

从文件中加载数据,然后将其传递给每个函数以插入到 mysql 和 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();
}
?>
登录后复制

执行示例

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

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

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

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

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

以上就是使用 PHP 自动将 CSV 和 Excel 数据导入 MySQL 和 PostgreSQL 数据库的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号