-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.php
74 lines (61 loc) · 2.63 KB
/
import.php
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
// Load file config.php
include "config.php";
// Load file autoload.php
require 'vendor/autoload.php';
// Include librari PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
// Establish a database connection
$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "unitedku_database";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
if (isset($_POST['import'])) { // Jika user mengklik tombol Import
$nama_file_baru = $_POST['namafile'];
$path = 'tmp/' . $nama_file_baru; // Set tempat menyimpan file tersebut dimana
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($path); // Load file yang tadi diupload ke folder tmp
$sheet = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
$numrow = 1;
foreach ($sheet as $row) {
// Ambil data pada excel sesuai Kolom
$product_name = $row['A']; // Ambil data nama
$product_image = $row['B']; // Ambil data jenis kelamin
$product_category = $row['C']; // Ambil data telepon
$product_price = $row['D']; // Ambil data alamat
$product_stock = $row['E']; // Ambil data alamat
$user_id = $row['F']; // Ambil data alamat
// Cek jika semua data tidak diisi
if ($product_name == "" && $product_image == "" && $product_category == "" && $product_price == "" && $product_stock == "" && $user_id == "")
continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris selanjutnya)
// Cek $numrow apakah lebih dari 1
// Artinya karena baris pertama adalah nama-nama kolom
// Jadi dilewat saja, tidak usah diimport
if ($numrow > 1) {
// Proses simpan ke Database
// Buat query Insert
$sql = $pdo->prepare("INSERT INTO table_product
(product_name, product_image, product_category, product_price, product_stock, user_id)
VALUES
(:product_name, :product_image, :product_category, :product_price, :product_stock, :user_id)");
$sql->execute([
'product_name' => $product_name,
'product_image' => $product_image,
'product_category' => $product_category,
'product_price' => $product_price,
'product_stock' => $product_stock,
'user_id' => $user_id,
]);
}
$numrow++; // Tambah 1 setiap kali looping
}
unlink($path); // Hapus file excel yg telah diupload, ini agar tidak terjadi penumpukan file
}
header('location: product_list.php'); // Redirect ke halaman awal