Membuat char dengan PHP, highchart, MySql dan Bootstrap

Membuat char dengan PHP, highchart, MySql dan Bootstrap

Berikut adalah langkah-langkah untuk membuat chart dengan PHP, Highcharts, MySQL, dan Bootstrap, yang memungkinkan pengguna untuk memfilter data per bulan dan per tahun dengan fitur input data serta tombol navigasi antar halaman:

1. Struktur Database

Buat database dan tabel:

CREATE DATABASE highcharts_demo;

USE highcharts_demo;

CREATE TABLE sales (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sales_date DATE NOT NULL,
    amount DECIMAL(10, 2) NOT NULL
);

2. Halaman Input Data

File: input_data.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Data</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center">Input Data</h2>
        <?php if (isset($_GET['message'])): ?>
            <div class="alert alert-info">
                <?php echo htmlspecialchars($_GET['message']); ?>
            </div>
        <?php endif; ?>
        <form action="process_input.php" method="POST">
            <div class="mb-3">
                <label for="sales_date" class="form-label">Sales Date</label>
                <input type="date" id="sales_date" name="sales_date" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="amount" class="form-label">Amount</label>
                <input type="number" id="amount" name="amount" step="0.01" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        <a href="index.php" class="btn btn-secondary mt-3">Go to Chart</a>
    </div>
</body>
</html>
input data

3. Backend Input Data

File: process_input.php

<?php
$host = 'localhost';
$db = 'highcharts_demo';
$user = 'root'; // Sesuaikan
$pass = ''; // Sesuaikan

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sales_date = $_POST['sales_date'];
    $amount = $_POST['amount'];

    $stmt = $conn->prepare("INSERT INTO sales (sales_date, amount) VALUES (?, ?)");
    $stmt->bind_param("sd", $sales_date, $amount);

    if ($stmt->execute()) {
        $message = "Data successfully added!";
    } else {
        $message = "Failed to add data.";
    }

    $stmt->close();
    $conn->close();

    header("Location: input_data.php?message=" . urlencode($message));
    exit();
}
?>

4. Halaman Chart dengan Filter

File: index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Chart</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center">Sales Chart</h2>

        <!-- Filter Form -->
        <form id="filterForm" class="row g-3">
            <div class="col-md-4">
                <label for="filterType" class="form-label">Filter Type</label>
                <select id="filterType" name="filterType" class="form-select" required>
                    <option value="monthly">Monthly</option>
                    <option value="yearly">Yearly</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="filterValue" class="form-label">Filter Value</label>
                <input type="month" id="filterValue" name="filterValue" class="form-control" required>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
        </form>

        <!-- Chart Container -->
        <div id="chartContainer" style="width: 100%; height: 500px;" class="mt-4"></div>
        <a href="input_data.php" class="btn btn-secondary mt-3">Add Data</a>
    </div>

    <script>
        document.getElementById('filterForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const filterType = document.getElementById('filterType').value;
            const filterValue = document.getElementById('filterValue').value;

            fetch('fetch_data.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ filterType, filterValue }),
            })
                .then((response) => response.json())
                .then((data) => {
                    if (data.success) {
                        Highcharts.chart('chartContainer', {
                            chart: { type: 'line' },
                            title: { text: 'Sales Data' },
                            xAxis: { categories: data.categories },
                            yAxis: { title: { text: 'Amount' } },
                            series: [{
                                name: 'Sales',
                                data: data.amounts,
                            }],
                        });
                    } else {
                        alert('No data available.');
                    }
                });
        });
    </script>
</body>
</html>
sales chart

5. Backend Fetch Data

File: fetch_data.php

<?php
header('Content-Type: application/json');

$host = 'localhost';
$db = 'highcharts_demo';
$user = 'root';
$pass = '';

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'error' => 'Database connection failed']));
}

$input = json_decode(file_get_contents('php://input'), true);
$filterType = $input['filterType'];
$filterValue = $input['filterValue'];

$query = '';
if ($filterType === 'monthly') {
    $query = "SELECT sales_date, amount FROM sales WHERE DATE_FORMAT(sales_date, '%Y-%m') = ?";
} elseif ($filterType === 'yearly') {
    $query = "SELECT sales_date, amount FROM sales WHERE YEAR(sales_date) = ?";
}

$stmt = $conn->prepare($query);
$stmt->bind_param("s", $filterValue);

$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $categories = [];
    $amounts = [];
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row['sales_date'];
        $amounts[] = (float)$row['amount'];
    }
    echo json_encode(['success' => true, 'categories' => $categories, 'amounts' => $amounts]);
} else {
    echo json_encode(['success' => false]);
}

$stmt->close();
$conn->close();
?>

Struktur Folder

/project/
  - input_data.php
  - process_input.php
  - index.php
  - fetch_data.php

Dengan implementasi ini, form input data, chart dengan filter, dan tombol navigasi sudah saling terhubung. Data yang diinput langsung ditampilkan dalam chart sesuai filter. 🎉

Leave a Reply

Your email address will not be published. Required fields are marked *