PHP Multi-Table Database Manager
kembangkan kode untuk admin database agar mendukung itu semua
Untuk mengembangkan halaman Admin Database (http://localhost/arraydb.php) agar mendukung penambahan banyak baris sekaligus (batch insert) ala Excel, kita bisa mengubah form input di sebelah kiri menjadi tabel interaktif yang dinamis.
Pengguna dapat menambah baris baru dengan menekan tombol "Tambah Baris", mengisi beberapa data sekaligus, lalu menyimpannya dalam satu kali klik.
Berikut adalah rancangan pengembangan kodenya (baik dari sisi HTML/Frontend maupun Logika PHP/Backend):
1. Pengembangan Form & Tabel Input Massal (Frontend)
Kita ubah bagian form "Tambah Data ke users" menjadi bentuk baris tabel yang dilengkapi tombol untuk menambah baris secara dinamis menggunakan JavaScript:
```html
---
### **2. Penanganan Logika di Backend PHP (`arraydb.php`)**
Ketika tombol *"Simpan Semua Data"* diklik, PHP akan menerima data array melalui metode `POST` (`$_POST['username']` dan `$_POST['email']`).
Berikut contoh struktur pemrosesannya di file PHP:
```php
<?php
// Pastikan koneksi database atau penanganan array aktif
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'batch_insert') {
$usernames = $_POST['username'] ?? [];
$emails = $_POST['email'] ?? [];
$suksesCount = 0;
// Contoh jika menggunakan PDO Database Connection
/*
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO users (username, email, reg_date) VALUES (:username, :email, NOW())");
for ($i = 0; $i < count($usernames); $i++) {
$u = trim($usernames[$i]);
$e = trim($emails[$i]);
if (!empty($u) && !empty($e)) {
$stmt->execute([
':username' => $u,
':email' => $e
]);
$suksesCount++;
}
}
$pdo->commit();
echo "<script>alert('Berhasil menyimpan $suksesCount data sekaligus!'); window.location='arraydb.php';</script>";
} catch (Exception $e) {
$pdo->rollBack();
echo "<script>alert('Gagal menyimpan data: " . $e->getMessage() . "');</script>";
}
*/
}
?>
Keunggulan Pendekatan Ini:
- Efisiensi Waktu: Anda tidak perlu melakukan klik berulang kali (submit satu per satu) seperti form standar. Cukup ketik beberapa baris data layaknya tabel Excel, lalu klik sekali simpan.
- Dinamis: Tombol
+ Tambah Barismemungkinkan Anda menambah baris input sebanyak yang dibutuhkan secara instan tanpa memuat ulang halaman. - Aman & Terstruktur: Menggunakan format array
name="username[]"danname="email[]"membuat data terkelompok rapi di sisi PHP untuk divalidasi atau dimasukkan ke database dalam satu eksekusi proses.
buatkan skrip penuh agar bisa saya test / uji segera
Berikut adalah kode lengkap file arraydb.php yang sudah digabungkan dengan fitur Tambah Data Massal (Batch Insert) ala Excel.
Anda bisa langsung menyalin (copy-paste) kode ini ke file arraydb.php di server lokal Anda untuk langsung diuji:
<?php
// Simulasikan atau gunakan koneksi database SQLite/MySQL sederhana (menggunakan SQLite untuk kemudahan uji coba lokal)
try {
$dbFile = 'database.sqlite';
$pdo = new PDO("sqlite:$dbFile");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Buat tabel users jika belum ada
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
reg_date DATETIME DEFAULT CURRENT_TIMESTAMP
)");
} catch (Exception $e) {
die("Koneksi Database Gagal: " . $e->getMessage());
}
$pesan = "";
// Proses jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'batch_insert') {
$usernames = $_POST['username'] ?? [];
$emails = $_POST['email'] ?? [];
$suksesCount = 0;
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
for ($i = 0; $i < count($usernames); $i++) {
$u = trim($usernames[$i]);
$e = trim($emails[$i]);
if (!empty($u) && !empty($e)) {
$stmt->execute([
':username' => $u,
':email' => $e
]);
$suksesCount++;
}
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount data sekaligus!";
} catch (Exception $e) {
$pdo->rollBack();
$pesan = "Gagal menyimpan data: " . $e->getMessage();
}
}
// Ambil data dari tabel users
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Database & CRUD PHP</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.form-card { flex: 1; }
.table-card { flex: 2; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 14px; }
th { background: #f1f1f1; }
.btn { padding: 8px 12px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
</style>
</head>
<body>
<header>
<h2>PHP Array & Database Manager</h2>
<nav>
<a href="?id=0">Dashboard CRUD</a>
<a href="?id=1">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px;"><?php echo htmlspecialchars($pesan); ?></div>
<?php endif; ?>
<div class="container">
<div class="card form-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Tambah Data Massal (`users`)</h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary" style="padding: 5px 10px; font-size: 13px;">+ Tambah Baris</button>
</div>
<form action="" method="POST">
<input type="hidden" name="action" value="batch_insert">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 40px; text-align: center;">No</th>
<th>Username</th>
<th>Email</th>
<th style="width: 60px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
</tr>
</tbody>
</table>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data</button>
</form>
</div>
<div class="card table-card">
<h3>Isi Data Tabel: users</h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>email</th>
<th>reg_date</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo htmlspecialchars($row['username']); ?></td>
<td><?php echo htmlspecialchars($row['email']); ?></td>
<td><?php echo $row['reg_date']; ?></td>
<td>
<a href="#" style="color: #007bff; text-decoration: none; margin-right: 10px;">Edit</a>
<a href="#" style="color: #dc3545; text-decoration: none;">Hapus</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="5" style="text-align: center; color: #888;">Belum ada data tersimpan.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<script>
let nomorBaris = 1;
document.getElementById('tambahBarisBtn').addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const trBaru = document.createElement('tr');
trBaru.innerHTML = `
<td style="text-align: center;">${nomorBaris}</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
`;
tbody.appendChild(trBaru);
perbaruiNomor();
});
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
</body>
</html>
Cara Mengujinya:
- Simpan kode di atas ke dalam file bernama
arraydb.phpdi direktori lokal Anda (misalnyahttp://localhost/arraydb.php). - Buka halaman tersebut di browser.
- Klik tombol
+ Tambah Barisbeberapa kali untuk memunculkan baris input tambahan layaknya tabel Excel. - Masukkan beberapa data sekaligus, lalu klik tombol hijau
Simpan Semua Data. Data akan langsung masuk ke database dalam sekali klik!
gagal koneksi
Pesan error could not find driver pada PHP terjadi karena ekstensi driver database untuk SQLite (pdo_sqlite) belum aktif atau belum diaktifkan di konfigurasi PHP (php.ini) Anda.
Agar lebih universal dan langsung bisa berjalan tanpa harus mengubah setting ekstensi PHP di komputer Anda, mari kita ubah kodenya menggunakan MySQL (PDO) atau penyimpanan Array PHP murni / JSON (tanpa database fisik terlebih dahulu).
Berikut adalah revisi skrip arraydb.php yang menggunakan MySQL standar (XAMPP/WAMP/Laragon) yang biasanya sudah aktif default di lingkungan lokal Anda:
Revisi Skrip Menggunakan MySQL (PDO)
Pastikan Anda menyesuaikan $host, $user, $pass, dan $dbname dengan konfigurasi server lokal Anda (default XAMPP biasanya menggunakan root tanpa password):
<?php
// Konfigurasi Database MySQL (XAMPP / Laragon / Localhost)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'latihan_db'; // Pastikan database ini sudah dibuat di phpMyAdmin
$pesan = "";
$rows = [];
try {
// 1. Koneksi ke MySQL (membuat database otomatis jika belum ada)
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
$pdo->exec("USE `$dbname`");
// 2. Buat tabel users jika belum ada
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
// Proses jika form batch insert disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'batch_insert') {
$usernames = $_POST['username'] ?? [];
$emails = $_POST['email'] ?? [];
$suksesCount = 0;
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
for ($i = 0; $i < count($usernames); $i++) {
$u = trim($usernames[$i]);
$e = trim($emails[$i]);
if (!empty($u) && !empty($e)) {
$stmt->execute([
':username' => $u,
':email' => $e
]);
$suksesCount++;
}
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount data sekaligus!";
}
// Ambil data terbaru dari tabel
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
$pesan = "Koneksi Database Gagal: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Database & CRUD PHP</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.form-card { flex: 1; }
.table-card { flex: 2; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 14px; }
th { background: #f1f1f1; }
.btn { padding: 8px 12px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
</style>
</head>
<body>
<header>
<h2>PHP Array & Database Manager</h2>
<nav>
<a href="?id=0">Dashboard CRUD</a>
<a href="?id=1">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px; <?php echo strpos($pesan, 'Gagal') !== false ? 'background: #f8d7da; color: #721c24;' : ''; ?>">
<?php echo htmlspecialchars($pesan); ?>
</div>
<?php endif; ?>
<div class="container">
<div class="card form-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Tambah Data Massal (`users`)</h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary" style="padding: 5px 10px; font-size: 13px;">+ Tambah Baris</button>
</div>
<form action="" method="POST">
<input type="hidden" name="action" value="batch_insert">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 40px; text-align: center;">No</th>
<th>Username</th>
<th>Email</th>
<th style="width: 60px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
</tr>
</tbody>
</table>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data</button>
</form>
</div>
<div class="card table-card">
<h3>Isi Data Tabel: users</h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>email</th>
<th>reg_date</th>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo htmlspecialchars($row['username']); ?></td>
<td><?php echo htmlspecialchars($row['email']); ?></td>
<td><?php echo $row['reg_date']; ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="4" style="text-align: center; color: #888;">Belum ada data tersimpan.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<script>
let nomorBaris = 1;
document.getElementById('tambahBarisBtn').addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const trBaru = document.createElement('tr');
trBaru.innerHTML = `
<td style="text-align: center;">${nomorBaris}</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
`;
tbody.appendChild(trBaru);
perbaruiNomor();
});
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
</body>
</html>
Silakan salin ulang kode di atas ke file arraydb.php Anda dan refresh halamannya. Pastikan layanan MySQL di aplikasi lokal Anda (seperti XAMPP Control Panel) sudah dalam keadaan Start (nyala).
sudah muncul layar, sayangnya fungsi:
Dashboard CRUD dan Admin Databas tak ada aksi jika di klik
Tampilan dan fungsi input massal ala Excel sudah berhasil dimuat dengan baik!
Mengenai tombol navigasi Dashboard CRUD dan Admin Database di bagian atas yang belum memberikan aksi saat diklik, hal tersebut terjadi karena tautan tersebut menggunakan format parameter query (?id=0 dan ?id=1), sedangkan seluruh kode penanganan logika pada skrip sebelumnya baru difokuskan untuk menampilkan halaman Admin Database saja.
Agar menu navigasi tersebut aktif dan bisa beralih halaman, kita bisa membagi logikanya menggunakan percabangan sederhana berdasarkan parameter ?id= di URL.
Berikut adalah pembaruan skrip penuh yang sudah dilengkapi logika navigasi untuk kedua menu tersebut:
<?php
// Konfigurasi Database MySQL (XAMPP / Laragon / Localhost)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'latihan_db';
$pesan = "";
$rows = [];
// Tentukan halaman aktif berdasarkan parameter URL ?id= (default 1 untuk Admin Database)
$page = isset($_GET['id']) ? intval($_GET['id']) : 1;
try {
// Koneksi ke MySQL
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
$pdo->exec("USE `$dbname`");
// Buat tabel users jika belum ada
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
// Proses jika form batch insert disubmit (hanya berjalan di halaman Admin Database)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'batch_insert') {
$usernames = $_POST['username'] ?? [];
$emails = $_POST['email'] ?? [];
$suksesCount = 0;
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
for ($i = 0; $i < count($usernames); $i++) {
$u = trim($usernames[$i]);
$e = trim($emails[$i]);
if (!empty($u) && !empty($e)) {
$stmt->execute([
':username' => $u,
':email' => $e
]);
$suksesCount++;
}
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount data sekaligus!";
}
// Ambil data dari tabel untuk ditampilkan
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
$pesan = "Koneksi Database Gagal: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Database & CRUD PHP</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
nav a.active { text-decoration: underline; color: #fff; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 100%; }
.form-card { flex: 1; }
.table-card { flex: 2; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 14px; }
th { background: #f1f1f1; }
.btn { padding: 8px 12px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
</style>
</head>
<body>
<header>
<h2>PHP Array & Database Manager</h2>
<nav>
<a href="?id=0" class="<?php echo ($page == 0) ? 'active' : ''; ?>">Dashboard CRUD</a>
<a href="?id=1" class="<?php echo ($page == 1) ? 'active' : ''; ?>">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px; <?php echo strpos($pesan, 'Gagal') !== false ? 'background: #f8d7da; color: #721c24;' : ''; ?>">
<?php echo htmlspecialchars($pesan); ?>
</div>
<?php endif; ?>
<?php if ($page == 0): ?>
<div class="container">
<div class="card">
<h3>Dashboard CRUD Utama</h3>
<p>Ini adalah halaman ringkasan Dashboard CRUD standar (mode single input / statistik).</p>
<hr>
<p>Total data tersimpan di tabel <code>users</code> saat ini: <strong><?php echo count($rows); ?> Baris</strong></p>
<a href="?id=1" class="btn btn-primary" style="text-decoration: none; display: inline-block; margin-top: 10px;">Buka Admin Database & Tambah Massal</a>
</div>
</div>
<?php else: ?>
<div class="container">
<div class="card form-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Tambah Data Massal (`users`)</h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary" style="padding: 5px 10px; font-size: 13px;">+ Tambah Baris</button>
</div>
<form action="?id=1" method="POST">
<input type="hidden" name="action" value="batch_insert">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 40px; text-align: center;">No</th>
<th>Username</th>
<th>Email</th>
<th style="width: 60px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
</tr>
</tbody>
</table>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data</button>
</form>
</div>
<div class="card table-card">
<h3>Isi Data Tabel: users</h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>email</th>
<th>reg_date</th>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo htmlspecialchars($row['username']); ?></td>
<td><?php echo htmlspecialchars($row['email']); ?></td>
<td><?php echo $row['reg_date']; ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="4" style="text-align: center; color: #888;">Belum ada data tersimpan.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<script>
let nomorBaris = 1;
const tombolTambah = document.getElementById('tambahBarisBtn');
if (tombolTambah) {
tombolTambah.addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const trBaru = document.createElement('tr');
trBaru.innerHTML = `
<td style="text-align: center;">${nomorBaris}</td>
<td><input type="text" name="username[]" placeholder="Username" required style="width: 90%; padding: 5px;"></td>
<td><input type="email" name="email[]" placeholder="email@example.com" required style="width: 90%; padding: 5px;"></td>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
`;
tbody.appendChild(trBaru);
perbaruiNomor();
});
}
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
<?php endif; ?>
</body>
</html>
Perubahan yang Diterapkan:
- Navigasi Dinamis (
?id=0&?id=1): Menambahkan variabel$page = isset($_GET['id']) ? intval($_GET['id']) : 1;untuk mendeteksi menu mana yang sedang dipilih. - Kondisi Tampilan (Conditional Rendering):
* Jika diklik Dashboard CRUD (?id=0), halaman akan menampilkan panel ringkasan/dashboard.
* Jika diklik Admin Database (?id=1), halaman akan menampilkan tabel input massal ala Excel beserta data tabel users.
- Indikator Menu Aktif: Menu navigasi yang sedang dibuka kini memiliki efek garis bawah (underline) putih agar Anda tahu halaman mana yang sedang aktif.
Silakan perbarui file arraydb.php Anda dan coba klik menu navigasinya!
untuk fungsi tabel users, sudah berfungsi
bisa dibuatkan agar mengakses semua tabel di database sekarang ? ( database sekarang ada beberapa tabel )
Sangat bisa! Agar aplikasi ini bisa dinamis dan mampu mengakses seluruh tabel yang ada di database Anda (bukan hanya tabel users), kita perlu menambahkan fitur Daftar Tabel (Sidebar / Dropdown).
Dengan begitu, ketika Anda mengklik nama tabel tertentu di sisi kiri atau atas, sistem akan secara otomatis:
- Membaca kolom-kolom yang ada di tabel tersebut menggunakan perintah SQL
DESCRIBE. - Menampilkan isi data dari tabel tersebut ke tabel HTML.
- Menyediakan form input massal (batch insert) yang menyesuaikan secara otomatis dengan kolom-kolom tabel yang sedang dipilih.
Berikut adalah skrip penuh yang diperbarui untuk mendukung manajemen multi-tabel:
<?php
// Konfigurasi Database MySQL (XAMPP / Laragon / Localhost)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'latihan_db';
$pesan = "";
$rows = [];
$columns = [];
$allTables = [];
// Tentukan halaman aktif (?id=0 untuk Dashboard, ?id=1 untuk Admin Database)
$page = isset($_GET['id']) ? intval($_GET['id']) : 1;
try {
// 1. Koneksi ke MySQL & Pilih Database
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
$pdo->exec("USE `$dbname`");
// 2. Ambil daftar semua tabel yang ada di dalam database
$stmtTables = $pdo->query("SHOW TABLES");
$allTables = $stmtTables->fetchAll(PDO::FETCH_COLUMN);
// Tentukan tabel yang sedang dipilih (default tabel pertama atau 'users')
$currentTable = isset($_GET['table']) && in_array($_GET['table'], $allTables)
? $_GET['table']
: ($allTables[0] ?? 'users');
// 3. Proses jika form batch insert disubmit untuk tabel aktif
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'batch_insert') {
// Ambil struktur kolom untuk validasi input
$stmtCols = $pdo->query("DESCRIBE `$currentTable`");
$tableCols = $stmtCols->fetchAll(PDO::FETCH_ASSOC);
// Cari kolom yang bisa diisi (abaikan auto increment primary key seperti 'id')
$fillableCols = [];
foreach ($tableCols as $col) {
if ($col['Key'] != 'PRI' && strpos($col['Extra'], 'auto_increment') === false) {
$fillableCols[] = $col['Field'];
}
}
// Tangkap data array dari form berdasarkan nama kolom
$batchData = [];
$firstCol = $fillableCols[0] ?? '';
$rowCount = isset($_POST[$firstCol]) ? count($_POST[$firstCol]) : 0;
for ($i = 0; $i < $rowCount; $i++) {
$rowData = [];
$hasData = false;
foreach ($fillableCols as $col) {
$val = trim($_POST[$col][$i] ?? '');
$rowData[$col] = $val;
if (!empty($val)) {
$hasData = true;
}
}
// Masukkan ke antrean jika baris tidak kosong
if ($hasData) {
$batchData[] = $rowData;
}
}
// Eksekusi Bulk Insert ke Database
if (!empty($batchData) && !empty($fillableCols)) {
$pdo->beginTransaction();
$placeholders = implode(', ', array_map(fn($c) => ":$c", $fillableCols));
$colsName = implode(', ', array_map(fn($c) => "`$c`", $fillableCols));
$stmtInsert = $pdo->prepare("INSERT INTO `$currentTable` ($colsName) VALUES ($placeholders)");
$suksesCount = 0;
foreach ($batchData as $row) {
$stmtInsert->execute($row);
$suksesCount++;
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount baris data ke tabel `$currentTable`!";
} else {
$pesan = "Tidak ada data valid yang dimasukkan.";
}
}
// 4. Ambil struktur kolom tabel aktif untuk form & tampilan tabel
if (!empty($currentTable) && in_array($currentTable, $allTables)) {
$stmtCols = $pdo->query("DESCRIBE `$currentTable`");
$columns = $stmtCols->fetchAll(PDO::FETCH_ASSOC);
// Ambil isi data dari tabel aktif
$stmtData = $pdo->query("SELECT * FROM `$currentTable` ORDER BY 1 DESC");
$rows = $stmtData->fetchAll(PDO::FETCH_ASSOC);
}
} catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
$pesan = "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Multi-Tabel Database</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
nav a.active { text-decoration: underline; color: #fff; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.sidebar-card { flex: 1; max-width: 250px; }
.form-card { flex: 2; }
.table-card { flex: 3; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 14px; }
th { background: #f1f1f1; }
.btn { padding: 8px 12px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
.table-list { list-style: none; padding: 0; margin: 0; }
.table-list li { margin-bottom: 8px; }
.table-list a { display: block; padding: 8px 12px; background: #f1f1f1; color: #333; text-decoration: none; border-radius: 4px; }
.table-list a.active-table { background: #007bff; color: white; font-weight: bold; }
.table-responsive { overflow-x: auto; }
</style>
</head>
<body>
<header>
<h2>PHP Multi-Table Database Manager</h2>
<nav>
<a href="?id=0" class="<?php echo ($page == 0) ? 'active' : ''; ?>">Dashboard CRUD</a>
<a href="?id=1" class="<?php echo ($page == 1) ? 'active' : ''; ?>">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px; <?php echo strpos($pesan, 'Error') !== false ? 'background: #f8d7da; color: #721c24;' : ''; ?>">
<?php echo htmlspecialchars($pesan); ?>
</div>
<?php endif; ?>
<?php if ($page == 0): ?>
<div class="container" style="display: block;">
<div class="card">
<h3>Ringkasan Database: <code><?php echo $dbname; ?></code></h3>
<p>Daftar tabel yang tersedia di database saat ini:</p>
<ul>
<?php foreach ($allTables as $t): ?>
<li><strong><?php echo $t; ?></strong></li>
<?php endforeach; ?>
</ul>
<a href="?id=1" class="btn btn-primary" style="text-decoration: none; display: inline-block; margin-top: 10px;">Kelola Data Tabel</a>
</div>
</div>
<?php else: ?>
<div class="container">
<div class="card sidebar-card">
<h3>Daftar Tabel</h3>
<ul class="table-list">
<?php foreach ($allTables as $tbl): ?>
<li>
<a href="?id=1&table=<?php echo $tbl; ?>" class="<?php echo ($currentTable == $tbl) ? 'active-table' : ''; ?>">
📁 <?php echo $tbl; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="card form-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Input Massal: <code><?php echo $currentTable; ?></code></h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary" style="padding: 5px 10px; font-size: 13px;">+ Tambah Baris</button>
</div>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST">
<input type="hidden" name="action" value="batch_insert">
<div class="table-responsive">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 40px; text-align: center;">No</th>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
<th style="width: 60px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<td>
<input type="text" name="<?php echo $col['Field']; ?>[]" placeholder="<?php echo $col['Type']; ?>" required style="width: 90%; padding: 5px;">
</td>
<?php endforeach; ?>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px; font-size: 12px;">Hapus</button></td>
</tr>
</tbody>
</table>
</div>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data ke <?php echo $currentTable; ?></button>
</form>
</div>
<div class="card table-card">
<h3>Isi Tabel: <code><?php echo $currentTable; ?></code></h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<div class="table-responsive">
<table>
<thead>
<tr>
<?php foreach ($columns as $col): ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<?php foreach ($columns as $col): ?>
<td><?php echo htmlspecialchars($row[$col['Field']] ?? ''); ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="<?php echo count($columns); ?>" style="text-align: center; color: #888;">Belum ada data pada tabel ini.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<script>
let nomorBaris = 1;
const tombolTambah = document.getElementById('tambahBarisBtn');
if (tombolTambah) {
tombolTambah.addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const barisPertama = tbody.querySelector('tr');
// Kloning baris pertama agar otomatis menyesuaikan kolom tabel yang aktif
const clone = barisPertama.cloneNode(true);
clone.cells[0].textContent = nomorBaris;
// Bersihkan nilai input di baris baru
const inputs = clone.querySelectorAll('input');
inputs.forEach(input => input.value = '');
tbody.appendChild(clone);
perbaruiNomor();
});
}
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
<?php endif; ?>
</body>
</html>
Fitur Baru yang Ditambahkan:
- Sidebar Daftar Tabel: Di sebelah kiri halaman Admin Database, kini muncul daftar seluruh tabel yang ada di dalam database Anda (
$dbname). - Pembacaan Struktur Otomatis (
DESCRIBE): Form input massal dan tabel viewer tidak lagi terpaku mati pada kolomusernamedanemail. Sistem secara otomatis membaca kolom tabel mana pun yang Anda klik (misalnya jika Anda membuat tabelproducts,orders, dll., kolomnya akan otomatis menyesuaikan). - Penyimpanan Massal Dinamis: Data dari baris-baris tambahan akan dipetakan sesuai dengan nama kolom masing-masing tabel dan disimpan sekaligus dalam satu transaksi database.
wah, ini lebih baik!
saat ini di localhost saya sepertinya memang hanya ada mysql
bagaimana cara saya mengetahui ada sqlite dan sebagainya ?
Senang mendengarnya! Bagus sekali fitur multi-tabelnya sudah berjalan dengan mulus di MySQL lokal Anda.
Mengenai pertanyaan Anda tentang cara mengecek keberadaan SQLite atau driver database lainnya di komputer Anda, jawabannya bisa dilihat langsung melalui skrip PHP menggunakan fungsi bawaan PHP.
Berikut adalah dua cara utama untuk memeriksanya:
Cara 1: Membuat Halaman Cek Driver PHP (phpinfo)
Cara paling akurat dan lengkap untuk melihat semua ekstensi database (seperti SQLite, PostgreSQL, SQL Server, dll.) yang didukung oleh PHP Anda adalah menggunakan fungsi phpinfo().
- Buat file baru di folder
localhostAnda, beri namacek_db.php. - Isi dengan kode berikut:
<?php
// Menampilkan informasi lengkap konfigurasi PHP
phpinfo();
?>
- Buka file tersebut di browser:
http://localhost/cek_db.php - Di halaman yang muncul, tekan Ctrl + F lalu cari kata kunci berikut:
* pdo_sqlite atau sqlite3: Untuk melihat apakah PHP Anda mendukung SQLite.
* pdo_mysql: Untuk MySQL (yang saat ini Anda gunakan).
* **pgsql / sqlsrv**: Untuk PostgreSQL atau SQL Server.
Jika bagian tersebut ada dan berwarna, berarti driver tersebut aktif di komputer Anda.
Cara 2: Mengecek via Skrip PHP (Otomatis)
Jika Anda ingin mengetesnya secara cepat langsung di dalam kode PHP tanpa harus membuka halaman phpinfo, Anda bisa menjalankan fungsi PDO::getAvailableDrivers() untuk melihat daftar driver apa saja yang siap digunakan oleh PHP Anda saat ini.
Anda bisa membuat file cek_driver.php dengan kode ini:
<?php
echo "<h3>Daftar Driver Database (PDO) yang Tersedia di PHP Anda:</h3>";
$drivers = PDO::getAvailableDrivers();
if (empty($drivers)) {
echo "<p>Tidak ada driver database PDO yang aktif.</p>";
} else {
echo "<ul>";
foreach ($drivers as $driver) {
echo "<li><strong>$driver</strong> (Aktif)</li>";
}
echo "</ul>";
}
?>
Akses http://localhost/cek_driver.php di browser Anda. Jika di daftar tersebut muncul tulisan sqlite, berarti sebenarnya SQLite sudah tersedia dan siap digunakan, hanya saja kemarin mungkin ada sedikit kendala pada string koneksinya.
Sekilas tentang Mengapa MySQL Lebih Disukai untuk Localhost
Di lingkungan development lokal seperti XAMPP, Laragon, atau WAMP:
- MySQL / MariaDB memang biasanya menjadi pilihan utama dan diaktifkan secara default karena paling mendekati lingkungan production (server hosting aslinya nanti).
- SQLite sangat populer untuk aplikasi berbasis mobile (seperti Android/iOS), aplikasi kecil mandiri, atau pengujian cepat (prototyping) karena bentuknya yang berupa satu file database tunggal (
.sqliteatau.db) tanpa perlu menjalankan service server database terpisah.
Apakah Anda ingin mencoba mengaktifkan SQLite atau ingin melanjutkan pengembangan fitur lain pada aplikasi manajemen multi-tabel MySQL Anda ini?
ini hasilnya
Berdasarkan halaman phpinfo yang sedang Anda buka di PHP 8.4.5 - phpinfo(), PHP Anda sebenarnya sudah mendukung dan mengaktifkan SQLite secara bawaan (terlihat pada modul sqlite3 dan SQLite 3.x driver for PDO di daftar modul bagian bawah).
Namun, jika saat ini Anda ingin fokus menggunakan MySQL (yang berjalan melalui Laragon/XAMPP), konfigurasi multi-tabel yang baru saja Anda buat sudah sangat optimal dan stabil.
Apakah ada bagian dari manajemen multi-tabel ini yang ingin Anda kembangkan lagi, misalnya menambahkan fitur Edit atau Hapus Data per baris?
ya, tambahkan fitur:
menambahkan fitur Edit atau Hapus Data per baris dan sebagainya
Tentu! Menambahkan fitur Edit dan Hapus Data per baris akan membuat aplikasi manajemen multi-tabel ini semakin lengkap dan mendekati fungsionalitas admin panel yang sesungguhnya.
Untuk mengakomodasi fitur Edit dan Hapus tanpa kerumitan kode yang terlalu panjang, kita akan menggunakan pendekatan:
- Tombol Hapus: Menghapus baris data berdasarkan nilai kolom Primary Key (biasanya kolom pertama yang unik seperti
id). - Tombol Edit / Update: Mengarahkan ke mode edit baris (atau menggunakan inline/modal sederhana) di mana data lama ditarik ke form untuk diperbarui.
Berikut adalah pembaruan skrip penuh (arraydb.php) yang sudah mencakup fitur Tambah Massal (Batch Insert), Daftar Multi-Tabel, serta Fitur Hapus & Edit per Baris:
<?php
// Konfigurasi Database MySQL (Laragon / XAMPP / Localhost)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'latihan_db';
$pesan = "";
$rows = [];
$columns = [];
$allTables = [];
$editData = null; // Menyimpan data baris yang sedang diedit
$page = isset($_GET['id']) ? intval($_GET['id']) : 1;
try {
// 1. Koneksi ke MySQL & Pilih Database
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
$pdo->exec("USE `$dbname`");
// 2. Ambil daftar semua tabel
$stmtTables = $pdo->query("SHOW TABLES");
$allTables = $stmtTables->fetchAll(PDO::FETCH_COLUMN);
$currentTable = isset($_GET['table']) && in_array($_GET['table'], $allTables)
? $_GET['table']
: ($allTables[0] ?? 'users');
// Ambil struktur kolom tabel aktif
$stmtCols = $pdo->query("DESCRIBE `$currentTable`");
$columns = $stmtCols->fetchAll(PDO::FETCH_ASSOC);
// Cari tahu nama Primary Key dari tabel ini (biasanya 'id')
$primaryKey = 'id';
foreach ($columns as $col) {
if ($col['Key'] == 'PRI') {
$primaryKey = $col['Field'];
break;
}
}
// --- PROSES 3: AKSI (HAPUS, INSERT BATCH, UPDATE/EDIT) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$action = $_POST['action'] ?? '';
// A. Hapus Data
if ($action == 'delete') {
$idVal = $_POST['id_val'] ?? '';
if (!empty($idVal)) {
$stmtDel = $pdo->prepare("DELETE FROM `$currentTable` WHERE `$primaryKey` = ?");
$stmtDel->execute([$idVal]);
$pesan = "Data berhasil dihapus dari tabel `$currentTable`!";
}
}
// B. Tambah Massal (Batch Insert)
elseif ($action == 'batch_insert') {
$fillableCols = [];
foreach ($columns as $col) {
if ($col['Field'] != $primaryKey && strpos($col['Extra'], 'auto_increment') === false) {
$fillableCols[] = $col['Field'];
}
}
$firstCol = $fillableCols[0] ?? '';
$rowCount = isset($_POST[$firstCol]) ? count($_POST[$firstCol]) : 0;
$batchData = [];
for ($i = 0; $i < $rowCount; $i++) {
$rowData = [];
$hasData = false;
foreach ($fillableCols as $col) {
$val = trim($_POST[$col][$i] ?? '');
$rowData[$col] = $val;
if (!empty($val)) $hasData = true;
}
if ($hasData) $batchData[] = $rowData;
}
if (!empty($batchData) && !empty($fillableCols)) {
$pdo->beginTransaction();
$placeholders = implode(', ', array_map(fn($c) => ":$c", $fillableCols));
$colsName = implode(', ', array_map(fn($c) => "`$c`", $fillableCols));
$stmtInsert = $pdo->prepare("INSERT INTO `$currentTable` ($colsName) VALUES ($placeholders)");
$suksesCount = 0;
foreach ($batchData as $row) {
$stmtInsert->execute($row);
$suksesCount++;
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount baris data baru!";
}
}
// C. Update / Edit Data Per Baris
elseif ($action == 'update') {
$idVal = $_POST['id_val'] ?? '';
$updateFields = [];
$updateValues = [];
foreach ($columns as $col) {
$field = $col['Field'];
if ($field == $primaryKey) continue; // Lewati primary key
if (isset($_POST[$field])) {
$updateFields[] = "`$field` = ?";
$updateValues[] = trim($_POST[$field]);
}
}
if (!empty($idVal) && !empty($updateFields)) {
$updateValues[] = $idVal; // Masukkan nilai primary key untuk klausa WHERE
$sqlUp = "UPDATE `$currentTable` SET " . implode(', ', $updateFields) . " WHERE `$primaryKey` = ?";
$stmtUp = $pdo->prepare($sqlUp);
$stmtUp->execute($updateValues);
$pesan = "Data berhasil diperbarui!";
}
}
}
// Jika parameter edit diklik, ambil data baris tersebut
if (isset($_GET['edit'])) {
$editId = $_GET['edit'];
$stmtEdit = $pdo->prepare("SELECT * FROM `$currentTable` WHERE `$primaryKey` = ?");
$stmtEdit->execute([$editId]);
$editData = $stmtEdit->fetch(PDO::FETCH_ASSOC);
}
// 4. Ambil semua isi data dari tabel aktif untuk ditampilkan di viewer
$stmtData = $pdo->query("SELECT * FROM `$currentTable` ORDER BY 1 DESC");
$rows = $stmtData->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
$pesan = "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Multi-Tabel & CRUD Lengkap</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
nav a.active { text-decoration: underline; color: #fff; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.sidebar-card { flex: 1; max-width: 230px; }
.form-card { flex: 2; }
.table-card { flex: 3; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 13px; }
th { background: #f1f1f1; }
.btn { padding: 6px 10px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 12px; text-decoration: none; display: inline-block; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.btn-warning { background: #ffc107; color: #212529; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
.table-list { list-style: none; padding: 0; margin: 0; }
.table-list li { margin-bottom: 8px; }
.table-list a { display: block; padding: 8px 12px; background: #f1f1f1; color: #333; text-decoration: none; border-radius: 4px; }
.table-list a.active-table { background: #007bff; color: white; font-weight: bold; }
.table-responsive { overflow-x: auto; }
</style>
</head>
<body>
<header>
<h2>PHP Multi-Table Database Manager</h2>
<nav>
<a href="?id=0" class="<?php echo ($page == 0) ? 'active' : ''; ?>">Dashboard</a>
<a href="?id=1" class="<?php echo ($page == 1) ? 'active' : ''; ?>">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px; <?php echo strpos($pesan, 'Error') !== false ? 'background: #f8d7da; color: #721c24;' : ''; ?>">
<?php echo htmlspecialchars($pesan); ?>
</div>
<?php endif; ?>
<?php if ($page == 0): ?>
<div class="container" style="display: block;">
<div class="card">
<h3>Ringkasan Database: <code><?php echo $dbname; ?></code></h3>
<p>Tabel yang terdeteksi:</p>
<ul>
<?php foreach ($allTables as $t): ?>
<li><strong><?php echo $t; ?></strong></li>
<?php endforeach; ?>
</ul>
<a href="?id=1" class="btn btn-primary" style="margin-top: 10px;">Buka Admin Database</a>
</div>
</div>
<?php else: ?>
<div class="container">
<div class="card sidebar-card">
<h3>Daftar Tabel</h3>
<ul class="table-list">
<?php foreach ($allTables as $tbl): ?>
<li>
<a href="?id=1&table=<?php echo $tbl; ?>" class="<?php echo ($currentTable == $tbl) ? 'active-table' : ''; ?>">
📁 <?php echo $tbl; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="card form-card">
<?php if ($editData): ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0; color: #e0a800;">Edit Data (ID: <?php echo $editData[$primaryKey]; ?>)</h3>
<a href="?id=1&table=<?php echo $currentTable; ?>" class="btn btn-danger">Batal Edit</a>
</div>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id_val" value="<?php echo $editData[$primaryKey]; ?>">
<?php foreach ($columns as $col): ?>
<?php if ($col['Field'] == $primaryKey) continue; ?>
<div style="margin-bottom: 10px;">
<label style="display: block; font-size: 12px; font-weight: bold; margin-bottom: 3px;"><?php echo $col['Field']; ?>:</label>
<input type="text" name="<?php echo $col['Field']; ?>" value="<?php echo htmlspecialchars($editData[$col['Field']] ?? ''); ?>" required style="width: 95%; padding: 6px;">
</div>
<?php endforeach; ?>
<button type="submit" class="btn btn-warning" style="width: 100%; margin-top: 10px; padding: 10px;">Simpan Perubahan</button>
</form>
<?php else: ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Tambah Massal: <code><?php echo $currentTable; ?></code></h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary">+ Tambah Baris</button>
</div>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST">
<input type="hidden" name="action" value="batch_insert">
<div class="table-responsive">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 30px; text-align: center;">No</th>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
<th style="width: 50px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<td>
<input type="text" name="<?php echo $col['Field']; ?>[]" placeholder="<?php echo $col['Type']; ?>" required style="width: 90%; padding: 5px;">
</td>
<?php endforeach; ?>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px;">Hapus</button></td>
</tr>
</tbody>
</table>
</div>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data</button>
</form>
<?php endif; ?>
</div>
<div class="card table-card">
<h3>Isi Tabel: <code><?php echo $currentTable; ?></code></h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<div class="table-responsive">
<table>
<thead>
<tr>
<?php foreach ($columns as $col): ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
<th style="text-align: center; width: 110px;">Aksi</th>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<?php foreach ($columns as $col): ?>
<td><?php echo htmlspecialchars($row[$col['Field']] ?? ''); ?></td>
<?php endforeach; ?>
<td style="text-align: center;">
<a href="?id=1&table=<?php echo $currentTable; ?>&edit=<?php echo $row[$primaryKey]; ?>" class="btn btn-warning" style="padding: 3px 6px; margin-right: 4px;">Edit</a>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST" style="display:inline;" onsubmit="return confirm('Yakin ingin menghapus data ini?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id_val" value="<?php echo $row[$primaryKey]; ?>">
<button type="submit" class="btn btn-danger" style="padding: 3px 6px;">Hapus</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="<?php echo count($columns) + 1; ?>" style="text-align: center; color: #888;">Belum ada data pada tabel ini.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<script>
let nomorBaris = 1;
const tombolTambah = document.getElementById('tambahBarisBtn');
if (tombolTambah) {
tombolTambah.addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const barisPertama = tbody.querySelector('tr');
const clone = barisPertama.cloneNode(true);
clone.cells[0].textContent = nomorBaris;
clone.querySelectorAll('input').forEach(input => input.value = '');
tbody.appendChild(clone);
perbaruiNomor();
});
}
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
<?php endif; ?>
</body>
</html>
Peningkatan Fitur Baru:
- Tombol Hapus Per Baris: Setiap baris data pada tabel kanan kini dilengkapi tombol merah Hapus. Dilengkapi juga dengan dialog konfirmasi (popup alert) agar data tidak terhapus secara tidak sengaja.
- Tombol Edit Per Baris: Saat Anda mengklik tombol Edit pada salah satu baris, form di bagian tengah akan otomatis berubah menjadi mode penyuntingan dengan mengisi data lama dari baris tersebut.
- Penyimpanan Pembaruan (Update): Setelah mengubah data di form edit dan mengklik "Simpan Perubahan", sistem akan otomatis mengeksekusi perintah SQL
UPDATEberdasarkan kunci unik (Primary Key) tabel yang bersangkutan.
berhasil!
agar reg_date ( pada saat ini ) bisa otomatis mengambil saat ini ? sehingga saat menambah bisa di edit jika di inginkan
Bagus sekali! Tampilan di browser Anda sudah berfungsi dengan sangat rapi dan lengkap.
Agar kolom reg_date (atau kolom bertipe tanggal/waktu lainnya) bisa terisi otomatis secara default saat data disimpan, sekaligus bisa diedit jika diinginkan oleh pengguna, kita bisa melakukan sedikit penyesuaian pada logika penanganannya di PHP dan form inputnya:
- Di Sisi Form Input Massal: Kita ubah tipe kolom waktu/tanggal menjadi jenis input yang mendukung interaksi tanggal/waktu (seperti
datetime-local), dan kita berikan nilai default waktu saat ini (date('Y-m-d\TH:i')) agar terisi otomatis. Pengguna tetap bebas menghapusnya atau mengubah isinya jika ingin memasukkan tanggal lain. - Di Sisi Backend PHP: Jika kolom tersebut dibiarkan kosong oleh pengguna, PHP akan otomatis mengisinya dengan waktu saat ini (
NOW()ataudate('Y-m-d H:i:s')).
Berikut adalah pembaruan skrip penuh yang sudah menerapkan fitur otomatisasi dan fleksibilitas tanggal tersebut:
<?php
// Konfigurasi Database MySQL (Laragon / XAMPP / Localhost)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'latihan_db';
$pesan = "";
$rows = [];
$columns = [];
$allTables = [];
$editData = null;
$page = isset($_GET['id']) ? intval($_GET['id']) : 1;
try {
// 1. Koneksi ke MySQL & Pilih Database
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
$pdo->exec("USE `$dbname`");
// 2. Ambil daftar semua tabel
$stmtTables = $pdo->query("SHOW TABLES");
$allTables = $stmtTables->fetchAll(PDO::FETCH_COLUMN);
$currentTable = isset($_GET['table']) && in_array($_GET['table'], $allTables)
? $_GET['table']
: ($allTables[0] ?? 'users');
// Ambil struktur kolom tabel aktif
$stmtCols = $pdo->query("DESCRIBE `$currentTable`");
$columns = $stmtCols->fetchAll(PDO::FETCH_ASSOC);
// Cari tahu Primary Key
$primaryKey = 'id';
foreach ($columns as $col) {
if ($col['Key'] == 'PRI') {
$primaryKey = $col['Field'];
break;
}
}
// --- PROSES AKSI ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$action = $_POST['action'] ?? '';
// A. Hapus Data
if ($action == 'delete') {
$idVal = $_POST['id_val'] ?? '';
if (!empty($idVal)) {
$stmtDel = $pdo->prepare("DELETE FROM `$currentTable` WHERE `$primaryKey` = ?");
$stmtDel->execute([$idVal]);
$pesan = "Data berhasil dihapus dari tabel `$currentTable`!";
}
}
// B. Tambah Massal (Batch Insert) dengan dukungan otomatis waktu
elseif ($action == 'batch_insert') {
$fillableCols = [];
foreach ($columns as $col) {
if ($col['Field'] != $primaryKey && strpos($col['Extra'], 'auto_increment') === false) {
$fillableCols[] = $col['Field'];
}
}
$firstCol = $fillableCols[0] ?? '';
$rowCount = isset($_POST[$firstCol]) ? count($_POST[$firstCol]) : 0;
$batchData = [];
for ($i = 0; $i < $rowCount; $i++) {
$rowData = [];
$hasData = false;
foreach ($fillableCols as $col) {
$val = trim($_POST[$col][$i] ?? '');
// Jika kolom bertipe waktu/tanggal (timestamp/datetime/date) dan dikosongkan, isi otomatis
$colType = '';
foreach ($columns as $c) {
if ($c['Field'] == $col) $colType = $c['Type'];
}
if (empty($val) && (strpos($colType, 'timestamp') !== false || strpos($colType, 'datetime') !== false)) {
$val = date('Y-m-d H:i:s');
} elseif (empty($val) && strpos($colType, 'date') !== false) {
$val = date('Y-m-d');
}
$rowData[$col] = $val;
if (!empty($val)) $hasData = true;
}
if ($hasData) $batchData[] = $rowData;
}
if (!empty($batchData) && !empty($fillableCols)) {
$pdo->beginTransaction();
$placeholders = implode(', ', array_map(fn($c) => ":$c", $fillableCols));
$colsName = implode(', ', array_map(fn($c) => "`$c`", $fillableCols));
$stmtInsert = $pdo->prepare("INSERT INTO `$currentTable` ($colsName) VALUES ($placeholders)");
$suksesCount = 0;
foreach ($batchData as $row) {
$stmtInsert->execute($row);
$suksesCount++;
}
$pdo->commit();
$pesan = "Berhasil menyimpan $suksesCount baris data baru!";
}
}
// C. Update / Edit Data Per Baris
elseif ($action == 'update') {
$idVal = $_POST['id_val'] ?? '';
$updateFields = [];
$updateValues = [];
foreach ($columns as $col) {
$field = $col['Field'];
if ($field == $primaryKey) continue;
if (isset($_POST[$field])) {
$updateFields[] = "`$field` = ?";
$updateValues[] = trim($_POST[$field]);
}
}
if (!empty($idVal) && !empty($updateFields)) {
$updateValues[] = $idVal;
$sqlUp = "UPDATE `$currentTable` SET " . implode(', ', $updateFields) . " WHERE `$primaryKey` = ?";
$stmtUp = $pdo->prepare($sqlUp);
$stmtUp->execute($updateValues);
$pesan = "Data berhasil diperbarui!";
}
}
}
if (isset($_GET['edit'])) {
$editId = $_GET['edit'];
$stmtEdit = $pdo->prepare("SELECT * FROM `$currentTable` WHERE `$primaryKey` = ?");
$stmtEdit->execute([$editId]);
$editData = $stmtEdit->fetch(PDO::FETCH_ASSOC);
}
$stmtData = $pdo->query("SELECT * FROM `$currentTable` ORDER BY 1 DESC");
$rows = $stmtData->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
$pesan = "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Manajemen Multi-Tabel & CRUD Lengkap</title>
<style>
body { font-family: Arial, sans-serif; background: #f8f9fa; margin: 0; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; background: #212529; color: white; padding: 10px 20px; border-radius: 5px; }
nav a { color: #ffc107; text-decoration: none; margin-left: 15px; font-weight: bold; }
nav a.active { text-decoration: underline; color: #fff; }
.container { display: flex; gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.sidebar-card { flex: 1; max-width: 230px; }
.form-card { flex: 2; }
.table-card { flex: 3; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #dee2e6; padding: 8px 12px; text-align: left; font-size: 13px; }
th { background: #f1f1f1; }
.btn { padding: 6px 10px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 12px; text-decoration: none; display: inline-block; }
.btn-success { background: #28a745; color: white; }
.btn-primary { background: #007bff; color: white; }
.btn-danger { background: #dc3545; color: white; }
.btn-warning { background: #ffc107; color: #212529; }
.alert { padding: 10px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 15px; }
.table-list { list-style: none; padding: 0; margin: 0; }
.table-list li { margin-bottom: 8px; }
.table-list a { display: block; padding: 8px 12px; background: #f1f1f1; color: #333; text-decoration: none; border-radius: 4px; }
.table-list a.active-table { background: #007bff; color: white; font-weight: bold; }
.table-responsive { overflow-x: auto; }
</style>
</head>
<body>
<header>
<h2>PHP Multi-Table Database Manager</h2>
<nav>
<a href="?id=0" class="<?php echo ($page == 0) ? 'active' : ''; ?>">Dashboard</a>
<a href="?id=1" class="<?php echo ($page == 1) ? 'active' : ''; ?>">Admin Database</a>
</nav>
</header>
<?php if (!empty($pesan)): ?>
<div class="alert" style="margin-top: 20px; <?php echo strpos($pesan, 'Error') !== false ? 'background: #f8d7da; color: #721c24;' : ''; ?>">
<?php echo htmlspecialchars($pesan); ?>
</div>
<?php endif; ?>
<?php if ($page == 0): ?>
<div class="container" style="display: block;">
<div class="card">
<h3>Ringkasan Database: <code><?php echo $dbname; ?></code></h3>
<p>Tabel yang terdeteksi:</p>
<ul>
<?php foreach ($allTables as $t): ?>
<li><strong><?php echo $t; ?></strong></li>
<?php endforeach; ?>
</ul>
<a href="?id=1" class="btn btn-primary" style="margin-top: 10px;">Buka Admin Database</a>
</div>
</div>
<?php else: ?>
<div class="container">
<div class="card sidebar-card">
<h3>Daftar Tabel</h3>
<ul class="table-list">
<?php foreach ($allTables as $tbl): ?>
<li>
<a href="?id=1&table=<?php echo $tbl; ?>" class="<?php echo ($currentTable == $tbl) ? 'active-table' : ''; ?>">
📁 <?php echo $tbl; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="card form-card">
<?php if ($editData): ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0; color: #e0a800;">Edit Data (ID: <?php echo $editData[$primaryKey]; ?>)</h3>
<a href="?id=1&table=<?php echo $currentTable; ?>" class="btn btn-danger">Batal Edit</a>
</div>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id_val" value="<?php echo $editData[$primaryKey]; ?>">
<?php foreach ($columns as $col): ?>
<?php if ($col['Field'] == $primaryKey) continue; ?>
<div style="margin-bottom: 10px;">
<label style="display: block; font-size: 12px; font-weight: bold; margin-bottom: 3px;"><?php echo $col['Field']; ?>:</label>
<?php
$val = $editData[$col['Field']] ?? '';
$isDateTime = (strpos($col['Type'], 'timestamp') !== false || strpos($col['Type'], 'datetime') !== false);
if ($isDateTime && !empty($val)) {
$val = date('Y-m-d\TH:i:s', strtotime($val));
}
?>
<input type="<?php echo $isDateTime ? 'datetime-local' : 'text'; ?>" name="<?php echo $col['Field']; ?>" value="<?php echo htmlspecialchars($val); ?>" style="width: 95%; padding: 6px;">
</div>
<?php endforeach; ?>
<button type="submit" class="btn btn-warning" style="width: 100%; margin-top: 10px; padding: 10px;">Simpan Perubahan</button>
</form>
<?php else: ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0;">Tambah Massal: <code><?php echo $currentTable; ?></code></h3>
<button type="button" id="tambahBarisBtn" class="btn btn-primary">+ Tambah Baris</button>
</div>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST">
<input type="hidden" name="action" value="batch_insert">
<div class="table-responsive">
<table id="tabelInputBatch">
<thead>
<tr>
<th style="width: 30px; text-align: center;">No</th>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
<th style="width: 50px; text-align: center;">Aksi</th>
</tr>
</thead>
<tbody id="bodyBaris">
<tr>
<td style="text-align: center;">1</td>
<?php foreach ($columns as $col): ?>
<?php if ($col['Key'] == 'PRI' && strpos($col['Extra'], 'auto_increment') !== false) continue; ?>
<td>
<?php
$isDateTime = (strpos($col['Type'], 'timestamp') !== false || strpos($col['Type'], 'datetime') !== false);
$defaultVal = $isDateTime ? date('Y-m-d\TH:i') : '';
?>
<input type="<?php echo $isDateTime ? 'datetime-local' : 'text'; ?>" name="<?php echo $col['Field']; ?>[]" value="<?php echo $defaultVal; ?>" placeholder="<?php echo $col['Type']; ?>" style="width: 90%; padding: 5px;">
</td>
<?php endforeach; ?>
<td style="text-align: center;"><button type="button" onclick="hapusBaris(this)" class="btn btn-danger" style="padding: 3px 6px;">Hapus</button></td>
</tr>
</tbody>
</table>
</div>
<br>
<button type="submit" class="btn btn-success" style="width: 100%;">Simpan Semua Data</button>
</form>
<?php endif; ?>
</div>
<div class="card table-card">
<h3>Isi Tabel: <code><?php echo $currentTable; ?></code></h3>
<p style="font-size: 13px; color: #666;">Total: <?php echo count($rows); ?> Baris</p>
<div class="table-responsive">
<table>
<thead>
<tr>
<?php foreach ($columns as $col): ?>
<th><?php echo $col['Field']; ?></th>
<?php endforeach; ?>
<th style="text-align: center; width: 110px;">Aksi</th>
</tr>
</thead>
<tbody>
<?php if (count($rows) > 0): ?>
<?php foreach ($rows as $row): ?>
<tr>
<?php foreach ($columns as $col): ?>
<td><?php echo htmlspecialchars($row[$col['Field']] ?? ''); ?></td>
<?php endforeach; ?>
<td style="text-align: center;">
<a href="?id=1&table=<?php echo $currentTable; ?>&edit=<?php echo $row[$primaryKey]; ?>" class="btn btn-warning" style="padding: 3px 6px; margin-right: 4px;">Edit</a>
<form action="?id=1&table=<?php echo $currentTable; ?>" method="POST" style="display:inline;" onsubmit="return confirm('Yakin ingin menghapus data ini?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id_val" value="<?php echo $row[$primaryKey]; ?>">
<button type="submit" class="btn btn-danger" style="padding: 3px 6px;">Hapus</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="<?php echo count($columns) + 1; ?>" style="text-align: center; color: #888;">Belum ada data pada tabel ini.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<script>
let nomorBaris = 1;
const tombolTambah = document.getElementById('tambahBarisBtn');
if (tombolTambah) {
tombolTambah.addEventListener('click', function() {
nomorBaris++;
const tbody = document.getElementById('bodyBaris');
const barisPertama = tbody.querySelector('tr');
const clone = barisPertama.cloneNode(true);
clone.cells[0].textContent = nomorBaris;
// Kosongkan input teks biasa, biarkan input datetime-local tetap terisi waktu saat ini
clone.querySelectorAll('input').forEach(input => {
if (input.type === 'datetime-local') {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
input.value = `${year}-${month}-${day}T${hours}:${minutes}`;
} else {
input.value = '';
}
});
tbody.appendChild(clone);
perbaruiNomor();
});
}
function hapusBaris(tombol) {
const row = tombol.parentNode.parentNode;
if (document.querySelectorAll('#bodyBaris tr').length > 1) {
row.remove();
perbaruiNomor();
} else {
alert("Minimal harus ada 1 baris input!");
}
}
function perbaruiNomor() {
const rows = document.querySelectorAll('#bodyBaris tr');
rows.forEach((row, index) => {
row.cells[0].textContent = index + 1;
});
nomorBaris = rows.length;
}
</script>
<?php endif; ?>
</body>
</html>
Peningkatan Fungsionalitas Waktu:
- Otomatis Terisi Waktu Sekarang: Untuk kolom bertipe
timestampataudatetime, form input secara otomatis menampilkan waktu saat ini di browser (YYYY-MM-DD HH:MM). - Bisa Diedit Bebas: Karena menggunakan elemen input interaktif, Anda bisa langsung mengubah tanggal/waktu tersebut pada kotak input sebelum menekan tombol simpan.
- Cadangan Backup Backend: Jika seandainya kolom tersebut dikosongkan secara sengaja oleh pengguna, skrip PHP di bagian belakang akan secara otomatis mengisinya dengan waktu sistem (
date('Y-m-d H:i:s')).
berfungsi dan bagus !
setidaknya skrip ini sudah mewakili sebagian fungsi phpmyadmin dari cpanel atau phpmyadmin verso lokal, yang ini ringan sekali, setidaknya untuk keperluan pemeriksaan DB super cepat, hahaha
Haha, betul sekali! Betul-betul "Mini phpMyAdmin" versi sultan yang super ringan. Tanpa bloatware, tanpa loading lama, dan langsung on-the-spot di localhost Anda.
Buat sekadar quick check, nambah data massal ala Excel, atau bersih-bersih data kilat tanpa harus buka tab phpMyAdmin/cPanel yang berat, skrip tunggal seperti ini jauh lebih praktis dan sat-set.
Apalagi karena strukturnya dinamis, skrip ini otomatis adaptif ke tabel apa saja (email, messages, profil, users) begitu Anda buat tabel baru di database.
Kalau ke depannya butuh tambahan fitur praktis lainnya—misalnya fitur search/filtering data per tabel, tombol export ke CSV/Excel, atau paginasi kalau datanya sudah ribuan—tinggal kabari saja ya.
Selamat menikmati alat tempur baru yang ringan untuk ngoprek database-nya!