1

I want to display a chart with ApexCharts from MySQL data.

I am connecting to my database via axios and a php-file with functions that communicate with the database. A typical vue method looks like:

myfunction: function(){
  axios.post('ajaxfile.php', {
    request: 1,
  })
  .then(function (response) {
    alert(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  },

In ajaxfile.php this request is being continued like this and echoed back as json encoded:

if($request == 1){
$data = mysqli_query($con,"SELECT * from mytable");

  $result = array();
  while($row = mysqli_fetch_assoc($data)){
    $result[]=$row;
  }
  echo json_encode($result);
  exit;
}

ApexCharts pulls data in the data section of vue.js like this, which (in this case) is the base for a pie chart with 30% and 70% data:

data: {
    chartdata: [30, 70],
}

What I’d like to achieve is selecting two numeric values from my database in my ajaxfile.php and create a pie chart from it. So something like:

if($request == 1){
$data1 = mysqli_query($con,"SELECT * from mytable WHERE id=1");
  $result1 = mysqli_fetch_assoc($data1);

$data2 = mysqli_query($con,"SELECT * from mytable WHERE id=2");
  $result2 = mysqli_fetch_assoc($data2);

 $chartdata = $result1.','.$result2;

  echo json_encode($chartdata);
  exit;
}

And in Vue.js:

  myfunction: function(){
      axios.post('ajaxfile.php', {
        request: 1,
      })
      .then(function (response) {
        app.chartdata = response.data;
      })
      .catch(function (error) {
        console.log(error);
      });
      },

The chartdata from my ajaxfile should then be saved in app.chartdata in vue, so that ApexCharts can build the chart from it.

But how can I achieve the needed format?

[30,70]

I pretty much tried everything. Even rebuilding the format with additional brackets didn't help. Like:

app.chartdata ="[ "+app.chartdata +" ]";

1 Answer 1

2

There are way to do it in javascript, below is an approach to do it in MySQL.

When select * from mytable produces:

id
30
70

You can do select group_concat(id) as id from mytable, and get:

id
30,70

or even:

select concat('[',group_concat(id),']') as id from mytable

and get:

id
[30,70]
Sign up to request clarification or add additional context in comments.

1 Comment

This works! I think there might have been a problem trying to convert things in javascript. The approach to do it directly in mysql works perfectly! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.