A
A
Andrey Titov2021-08-02 12:17:30
PHP
Andrey Titov, 2021-08-02 12:17:30

How to correctly translate CSV to SQL in PHP?

Need help with code in CSV to SQL conversion file -

<?php

namespace TaskForce;

use Exceptions\TaskForceException;

class CSVToSQLConverter
{
    public $CSVFileObject;

    public function createSQLFromCSV($file, $directory): void
    {
        if (!file_exists($file)) {
            throw new TaskForceException('Файл не существует');
        }

        if (!file_exists($directory)  && !mkdir($directory)) {
            throw new TaskForceException('Не удалось создать дуректорию');
            mkdir($directory);
        }

        try {
            $this->CSVFileObject = new \SplFileObject($file, 'r');
        } catch (TaskForceException $exception) {
            throw new TaskForceException('Не удалось открыть файл на чтение');
        }

        $this->CSVFileObject->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_CSV);

        $headerData = implode(', ', $this->getHeaderData());

        $values[] =
            sprintf(
                "\t(%s)",
                implode(', ', array_map(function ($item) {
                    return "'{$item}'";
                }, $this->CSVFileObject->fgetcsv(',')))
            );

        // var_dump($values);

        $newFile = basename($file, '.csv');

        try {
            $SQLFileObject = new \SplFileObject("$directory/$newFile.sql", 'w');
        } catch (TaskForceException $exception) {
            throw new TaskForceException('Не удалось создать или записать в файл');
        }

        $SQLFileObject->fwrite("INSERT INTO $newFile ($headerData) VALUES {implode(', ' , $values)};");
    }

    public function getHeaderData(): ?array
    {
        $data = $this->CSVFileObject->fgetcsv();

        return $data;
    }
}

The file is generated, but not as expected. I think that something is not quite right in the line
$SQLFileObject->fwrite("INSERT INTO $newFile ($headerData) VALUES {implode(', ' , $values)};");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2021-08-02
@ThunderCat

cli + mysqlimport

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question