Въз основа на това, което ми предоставихте, събрах следния PHP клас, който, надявам се, трябва да ви предостави функционалността, от която се нуждаете. Долната част на кода демонстрира използването на малкия клас.
<?php
class CSVtoSQL {
private $filePath, $csvData;
public function __construct($filePath) {
$this->filePath = $filePath;
}
public function readDataIn() {
$file = fopen($this->filePath, 'r');
$data = fread($file, filesize($this->filePath));
// Split CSV line by line.
$lines = explode("\n", $data);
// Split each line by commas to extract each value.
for ($i = 0; $i < sizeof($lines); $i++) {
$this->csvData[$i] = explode(',', $lines[$i]);
}
fclose($file);
// Returns true if we managed to read data, false if we didn't.
return (sizeof($this->csvData) > 0);
}
public function getHeadings() {
if (sizeof($this->csvData) > 0) {
// The first index of csvData has all the headings.
return $this->csvData[0];
}
else {
return null;
}
}
public function pushToDatabase($con, $tableName, $columns) {
$createColumnQuery = '';
$insertQuery = 'INSERT INTO ' . $tableName . ' (';
// Build column section of query.
foreach ($columns as $column) {
$createColumnQuery .= $column['name'] . ' ' . $column['type'] . ',';
}
// Remove trailing comma.
$createColumnQuery = rtrim($createColumnQuery, ',');
// Create table.
$con->query('CREATE TABLE ' . $tableName . ' (' . $createColumnQuery . ')');
// Create insert query template.
foreach ($columns as $column) {
$insertQuery .= $column['name'] . ',';
}
// Remove trailing comma.
$insertQuery = rtrim($insertQuery, ',');
// Insert values using our insertQuery string which looks like: "INSERT INTO <<table name>> (<<column 1>>, <<column 2>>"
// Also skip the first line as that has the headings.
for ($i = 1; $i < sizeof($this->csvData); $i++) {
$values = '';
foreach($this->csvData[$i] as $value) {
$values .= '\'' . $value . '\',';
}
// Remove trailing comma.
$values = rtrim($values, ',');
$con->query($insertQuery . ') VALUES (' . $values . ')');
}
}
}
$csv = new CSVtoSQL('test.csv');
$csv->readDataIn();
var_dump($csv->getHeadings());
$con = new mysqli('127.0.0.1', 'root', '', 'testdb');
$columns = array(array('name'=>'col1', 'type'=>'VARCHAR(256)'),
array('name'=>'col2', 'type'=>'VARCHAR(256)'),
array('name'=>'col3', 'type'=>'VARCHAR(256)'));
$csv->pushToDatabase($con, 'test_table', $columns);
?>
Когато създавате нов обект от класа CSVtoSQL, преминете през пътя към CSV файла (това може да бъде относително или абсолютно). След това извикайте процедурата readDataIn(), за да отворите CSV, да извадите редовете и да ги съхраните в обекта. След това можете по избор да извлечете масив от заглавия, намерени в CSV, като извикате getHeadings(). Това ще бъде полезно за вас, когато искате да подканите потребителя към кои колони на базата данни желае да съпостави всяко CSV заглавие. И накрая, извикайте pushToDatabase() и осигурете MySQLi обект за свързване, име на таблица и данни за колона, както е показано.
За мен е тривиално да напиша формуляра за качване вместо вас, но този клас трябва да ви помогне да решите проблема си.
Късмет!
person
Shane Reeves
schedule
24.05.2014