-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.class.php
More file actions
74 lines (64 loc) · 2.4 KB
/
csv.class.php
File metadata and controls
74 lines (64 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
require_once 'config.php';
class Csv
{
public $table, $columns, $data, $seperator, $linebreak, $global, $enclosure, $rows;
public function __construct(string $table, array $columns, string $string, string $seperator, string $linebreak, array $global = [], string $enclosure = "")
{
$rows = str_getcsv($string, $linebreak);
for ($i = 0; $i < count($rows); $i++)
$data[$i] = str_getcsv($rows[$i], $seperator, $enclosure);
$this->table = $table;
$this->columns = $columns;
$this->data = $data;
$this->seperator = $seperator;
$this->linebreak = $linebreak;
$this->global = $global;
$this->enclosure = $enclosure;
$this->rows = $rows;
}
public function add()
{
for ($i = 0; $i < count($this->data); $i++)
self::addRow($this->data[$i]);
}
private function addRow($row)
{
global $pdo;
$sql = "INSERT INTO {$this->table} (";
$sql .= implode(", ", $this->columns);
$sql .= ") VALUES (";
if ($this->global)
{
for ($i = 0; $i < count($this->columns); $i++)
{
if (array_key_exists($this->columns[$i], $this->global))
$sql .= "'" . $this->global[$this->columns[$i]] . "'";
if (isset($row[$i]))
$sql .= "'" . $row[$i] . "'";
if ($i < count($this->columns)-1)
$sql .= ", ";
}
$sql .= ")";
}
else
$sql .= "'" . implode("', '", $row) . "')";
$sth = $pdo->prepare($sql);
$sth->execute();
}
public function checkForError()
{
$errorCounter = 0;
$rowsWithError = [];
for ($i = 0; $i < count($this->data); $i++)
{
if (count($this->data[$i]) != (count($this->columns) - count($this->global)))
{
array_push($rowsWithError, $i);
$errorCounter++;
}
}
if ($errorCounter > 0)
Response::error(array_merge(Response::INSERT_ERROR, ["message" => Response::INSERT_ERROR["message"] . ". $errorCounter row(s) with errors: line(s) " . implode(", ", $rowsWithError) . ". " . count($this->columns) . " columns expected. No rows were inserted", "INSERT_ERROR"]), ["rows" => $rowsWithError]);
}
}