103 lines
3.2 KiB
PHP
103 lines
3.2 KiB
PHP
<?php
|
|
ini_set('display_errors', 0); // Disable error display for production
|
|
header('Content-Type: application/json');
|
|
|
|
require_once 'db/config.php';
|
|
|
|
// Initialize response array
|
|
$response = ['success' => false, 'error' => '', 'members' => []];
|
|
|
|
// Get action from request, default to 'list'
|
|
$action = $_REQUEST['action'] ?? 'list';
|
|
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
switch ($action) {
|
|
case 'list':
|
|
$stmt = $pdo->query("SELECT id, name, nik, address, phone FROM members ORDER BY created_at DESC");
|
|
$response['members'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
$response['success'] = true;
|
|
break;
|
|
|
|
case 'add':
|
|
// Simple validation
|
|
if (empty($_POST['name']) || empty($_POST['nik'])) {
|
|
throw new Exception('Nama dan NIK tidak boleh kosong.');
|
|
}
|
|
|
|
$sql = "INSERT INTO members (name, nik, address, phone) VALUES (:name, :nik, :address, :phone)";
|
|
$stmt = $pdo->prepare($sql);
|
|
|
|
$stmt->execute([
|
|
':name' => $_POST['name'],
|
|
':nik' => $_POST['nik'],
|
|
':address' => $_POST['address'] ?? '',
|
|
':phone' => $_POST['phone'] ?? ''
|
|
]);
|
|
|
|
$response['success'] = true;
|
|
break;
|
|
|
|
case 'get':
|
|
if (empty($_GET['id'])) {
|
|
throw new Exception('ID anggota tidak valid.');
|
|
}
|
|
$stmt = $pdo->prepare("SELECT id, name, nik, address, phone FROM members WHERE id = :id");
|
|
$stmt->execute([':id' => $_GET['id']]);
|
|
$member = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
if (!$member) {
|
|
throw new Exception('Anggota tidak ditemukan.');
|
|
}
|
|
$response['member'] = $member;
|
|
$response['success'] = true;
|
|
break;
|
|
|
|
case 'update':
|
|
if (empty($_POST['id']) || empty($_POST['name']) || empty($_POST['nik'])) {
|
|
throw new Exception('ID, Nama, dan NIK tidak boleh kosong.');
|
|
}
|
|
|
|
$sql = "UPDATE members SET name = :name, nik = :nik, address = :address, phone = :phone WHERE id = :id";
|
|
$stmt = $pdo->prepare($sql);
|
|
|
|
$stmt->execute([
|
|
':id' => $_POST['id'],
|
|
':name' => $_POST['name'],
|
|
':nik' => $_POST['nik'],
|
|
':address' => $_POST['address'] ?? '',
|
|
':phone' => $_POST['phone'] ?? ''
|
|
]);
|
|
|
|
$response['success'] = true;
|
|
break;
|
|
|
|
case 'delete':
|
|
if (empty($_POST['id'])) {
|
|
throw new Exception('ID anggota tidak valid.');
|
|
}
|
|
|
|
$sql = "DELETE FROM members WHERE id = :id";
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute([':id' => $_POST['id']]);
|
|
|
|
$response['success'] = true;
|
|
break;
|
|
|
|
default:
|
|
throw new Exception('Aksi tidak valid.');
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
$response['error'] = 'Database error: ' . $e->getMessage();
|
|
// Check for duplicate entry
|
|
if ($e->getCode() == 23000) {
|
|
$response['error'] = 'NIK sudah terdaftar.';
|
|
}
|
|
} catch (Exception $e) {
|
|
$response['error'] = $e->getMessage();
|
|
}
|
|
|
|
echo json_encode($response);
|