Files
d1041231004-webgis-spbu/api/jalan.php
T
2026-06-11 14:02:22 +07:00

81 lines
2.5 KiB
PHP

<?php
// api/jalan.php — CRUD untuk data Jalan (Polyline)
require_once 'config.php';
$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
switch ($method) {
case 'GET':
if ($id) {
$stmt = $db->prepare("SELECT * FROM jalan WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
echo json_encode($row ?: ['error' => 'Data tidak ditemukan']);
} else {
$res = $db->query("SELECT * FROM jalan ORDER BY id DESC");
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
echo json_encode($rows);
}
break;
case 'POST':
$body = json_decode(file_get_contents('php://input'), true);
$stmt = $db->prepare(
"INSERT INTO jalan (nama_jalan, status_jalan, panjang_m, geojson)
VALUES (?, ?, ?, ?)"
);
$stmt->bind_param(
'ssds',
$body['nama_jalan'], $body['status_jalan'],
$body['panjang_m'], $body['geojson']
);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'id' => $db->insert_id]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
case 'PUT':
$body = json_decode(file_get_contents('php://input'), true);
$stmt = $db->prepare(
"UPDATE jalan SET nama_jalan=?, status_jalan=?, panjang_m=?, geojson=?
WHERE id=?"
);
$stmt->bind_param(
'ssdsi',
$body['nama_jalan'], $body['status_jalan'],
$body['panjang_m'], $body['geojson'],
$body['id']
);
if ($stmt->execute()) {
echo json_encode(['success' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
case 'DELETE':
$stmt = $db->prepare("DELETE FROM jalan WHERE id=?");
$stmt->bind_param('i', $id);
if ($stmt->execute()) {
echo json_encode(['success' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
default:
http_response_code(405);
echo json_encode(['error' => 'Method tidak diizinkan']);
}
$db->close();