Creating a visually appealing pie chart using data from a specific database field is simpler than you think!

In the table field, I have 3 categories: "not yet, currently, done".

https://i.sstatic.net/bPXRz.png

My goal is to create a pie chart.

This is the model code snippet:

public function select_by_status() {
        $sql = "SELECT COUNT(status_laporan) AS jml FROM tp4d GROUP BY status_laporan ORDER BY jml";

        $data = $this->db->query($sql);

        return $data->row();
    }

Below is my controller code for generating the pie chart,

//statistic of reports
        $reports                = $this->M_reports->select_all();
        $index = 0;
        foreach ($reports as $value) {
            $color = '#' .$rand[rand(0,15)] .$rand[rand(0,15)] .$rand[rand(0,15)] .$rand[rand(0,15)] .$rand[rand(0,15)] .$rand[rand(0,15)];

            $report_status = $this->M_reports->select_by_status();

            $data_reports[$index]['value'] = $report_status->jml;
            $data_reports[$index]['color'] = $color;
            $data_reports[$index]['highlight'] = $color;
            $data_reports[$index]['label'] = $value->status_laporan;

            $index++;
        }
$data['data_reports'] = json_encode($data_reports);

Here is my view code:

<div class="col-lg-6 col-xs-12">
    <div class="box box-primary">
      <div class="box-header with-border">
        <i class="fa fa-briefcase"></i>
        <h3 class="box-title">Statistics <small>Report Status Data</small></h3>

        <div class="box-tools pull-right">
          <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
          </button>
          <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
        </div>
      </div>
      <div class="box-body">
        <canvas id="data-reports" style="height:250px"></canvas>
      </div>
    </div>
  </div>
</div>

And this is the script for generating the pie chart:

var pieChartCanvas = $("#data-reports").get(0).getContext("2d");
  var pieChart = new Chart(pieChartCanvas);
  var PieData = <?php echo $data_reports; ?>;

  var pieOptions = {
    segmentShowStroke: true,
    segmentStrokeColor: "#fff",
    segmentStrokeWidth: 2,
    percentageInnerCutout: 50,
    animationSteps: 100,
    animationEasing: "easeOutBounce",
    animateRotate: true,
    animateScale: false,
    responsive: true,
    maintainAspectRatio: true,
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
  };

  pieChart.Doughnut(PieData, pieOptions);

The issue I'm facing is that despite having different statuses in the database, the pie chart displays the same content. For example:

https://i.sstatic.net/xE337.png

https://i.sstatic.net/ZAxky.png

How can I ensure that the statistics on the pie chart accurately reflect the data from the database?

Answer №1

In my opinion, the information would be best stored as a JSON object.

To convert an object into JSON format, you can utilize json_encode($your_object), and then transfer it to JavaScript for further use.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animated scrolling in Angular

I am working on a webpage using Angular, where each module is a component with an animation. However, I am facing an issue where the animation only runs when the page loads, but I want it to happen while the component is visible on the screen. One approa ...

Trigger route handlers on both, successful authentication and failure, when using passport.js with a Node.js and Express.js REST API

Check out this simple login/token process using passport basic strategy for a Rest API: The Route: router.get('/token', authenticate.basic, controller.token); Authenticate Basic Strategy: authenticate.basic = passport.authenticate('basic ...

Incorporating SASS/SCSS syntax within the <style> element

Can I include SASS/SCSS syntax directly in an .html file within a style tag? I'm interested in defining a variable within the .html file and then utilizing it in a .sass file. ...

What is the process for embedding a single spa app into a basic HTML page?

Started off by creating a react app and then transforming it into a single spa react app using this tutorial. Upon hitting http://localhost:8080/org-app.js, I receive a response of the JavaScript files being loaded. Additionally, when I visit this link, t ...

Creating a dynamic circle that expands in size based on the duration the user presses down (using Java Script)

I have a fun challenge for you! I want to create a growing circle on a canvas based on how long you hold your mouse button. Currently, I can draw a fixed width circle where my mouse was when I clicked, but I need it to dynamically change size as you hold t ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Tips for minimizing the use of if-else statements in JavaScript (specifically in Node.js)

Depending on a specific parameter, the function needs to choose from over 100 JSON files and send a query to another system. There will be numerous queries, possibly in the hundreds. Using if else and switch statements would not be practical for managing ...

Show results from selecting multiple dropdown options

I am looking to create a search function that displays results based on multiple dropdown selections. I have 4 dropdown menus and a submit button, but I am unsure how to show the search results upon clicking the submit button. The desired outcome is to dis ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

Ensure that jquery.load is executed before the HTML content is loaded

Recently, I encountered a situation where I had a bootstrap navbar stored in a separate file, specifically named navbar.html. I utilized Jquery.load() to load this navbar into my HTML page. At the bottom of my HTML page, I included the following code: &l ...

Unable to locate required dependency

I've been attempting to download a template for customization, but after installing all local dependencies using npm install or yarn install, I consistently encounter the same error. I've tried running the commands with both --force and --legacy- ...

Issues with responsive design

Frontend mentor projects have been a tricky challenge for me lately, especially when it comes to serving images of different viewport sizes on desktop. I've tried using the picture element and specifying at what width the image should be served, but f ...

Choose an option from a list of items in a nested array by

I'm working with a nested array (3d) and I want to populate a drop-down select menu with its values using PHP and jQuery I've tried implementing this for two-level arrays like categories and sub-categories, but what if some sub-categories have f ...

Inline CSS not appearing correctly upon initial page load

Is your page rendering incorrectly on the first load but then correct after a refresh? It seems to be related to the "display:inline-block" style. Despite clearing cache before loading, the issue persists and you're unable to find a solution. First L ...

Compass - substitute a single value for an alternate attribute

Can I utilize a value from one class to customize another? Consider the following class: .sourceClass { color: red; } And now, let's say we have this class: .destinationClass { border-color: ###needs to match the color in .sourceClass => re ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Revamping the settings page by featuring a single "save changes" button

Is it possible to create a settings.php page where users can update their personal information, such as username, password, and email, all within the same page? I know how to perform these tasks individually, but I'm unsure about integrating different ...

Creating an image using tiles in HTML

I have divided an image into 48 tiles (8x6) using a method similar to "Cutting an Image into 9 pieces C#". Now, I want to reconstruct the original image in HTML. What is the most effective approach to achieve this? Initially, I attempted to use a table wi ...