溫馨提示×

php sqlhelper怎樣實(shí)現(xiàn)數(shù)據(jù)導(dǎo)入

PHP
小樊
81
2024-10-17 07:09:42
欄目: 云計(jì)算

要使用PHP和SQL Helper實(shí)現(xiàn)數(shù)據(jù)導(dǎo)入,首先確保你已經(jīng)創(chuàng)建了一個(gè)數(shù)據(jù)庫連接,并安裝了一個(gè)SQL Helper類。以下是一個(gè)簡單的示例,展示了如何使用這些工具將CSV文件中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫中:

  1. 安裝SQL Helper類。你可以從GitHub上下載它(https://github.com/PHPOffice/PhpSpreadsheet),或者使用Composer安裝:
composer require phpoffice/phpspreadsheet
  1. 創(chuàng)建一個(gè)CSV文件,例如data.csv,其中包含要導(dǎo)入到數(shù)據(jù)庫的數(shù)據(jù),如下所示:
id,name,email
1,John Doe,john@example.com
2,Jane Smith,jane@example.com
  1. 編寫一個(gè)PHP腳本,使用SQL Helper類將CSV數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫中。在這個(gè)例子中,我們將假設(shè)你的數(shù)據(jù)庫中有一個(gè)名為users的表,具有id,nameemail列。
<?php
// 引入自動加載文件
require 'vendor/autoload.php';

// 引入PhpSpreadsheet庫
use PhpOffice\PhpSpreadsheet\IOFactory;

// 數(shù)據(jù)庫連接信息
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';

// 創(chuàng)建數(shù)據(jù)庫連接
$conn = new mysqli($host, $username, $password, $dbname);

// 檢查連接
if ($conn->connect_error) {
    die("連接失敗: " . $conn->connect_error);
}

// 讀取CSV文件
$csvFile = 'data.csv';
$spreadsheet = IOFactory::load($csvFile);
$worksheet = $spreadsheet->getActiveSheet();

// 獲取表頭
$headers = $worksheet->getRowData(1);

// 準(zhǔn)備插入數(shù)據(jù)的SQL語句
$sql = "INSERT INTO users (id, name, email) VALUES ";
$values = [];

// 遍歷工作表中的數(shù)據(jù)行,并將數(shù)據(jù)插入到數(shù)據(jù)庫中
foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false); // 遍歷所有單元格,即使它們沒有值

    $rowData = [];
    foreach ($cellIterator as $cell) {
        $rowData[] = $cell->getValue();
    }

    // 跳過表頭行
    if ($row->getRowIndex() == 1) {
        continue;
    }

    // 為每個(gè)數(shù)據(jù)行構(gòu)建一個(gè)值數(shù)組,并添加到SQL語句中
    $values[] = "({$rowData[0]}, '{$rowData[1]}', '{$rowData[2]}')";
}

// 關(guān)閉數(shù)據(jù)庫連接
$conn->close();

// 執(zhí)行批量插入操作
$sql .= implode(', ', $values);
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->query($sql) === TRUE) {
    echo "數(shù)據(jù)導(dǎo)入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

這個(gè)腳本將讀取CSV文件中的數(shù)據(jù),并將其插入到名為users的數(shù)據(jù)庫表中。請確保根據(jù)你的實(shí)際情況修改數(shù)據(jù)庫連接信息和表名。

0