0

I am pulling some data from my database and turning it into an array which is perfect. I need to insert those into an object:

data: {
    labels: ["Red", "Remaining"],
    datasets: [{
        data: [90, 10], <-- here
        backgroundColor: [
            'rgba(255, 99, 132, 1)'
        ],
        borderWidth: 1
    }]

I am getting the data like so...

<?php
$sql = 'SELECT COUNT(*) category FROM users GROUP BY category';
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  while($row = mysqli_fetch_assoc($result)) {

      $categoriesTest[] =  $row["category"];

  }

}

?>

And turning it into a JavaScript variable like:

var dataString="<?php echo rtrim(implode(', ', $categoriesTest), ',');  ?>";

And here is the full code, bascially they will be the values for a chart.js chart.

<?php
$sql = 'SELECT COUNT(*) category FROM users GROUP BY category';
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  while($row = mysqli_fetch_assoc($result)) {

      $categoriesTest[] =  $row["category"];

  }

}

?>

<script>

var dataString="<?php echo rtrim(implode(', ', $categoriesTest), ',');  ?>";

document.write(dataString);

var ctx = document.getElementById("myChart");

var myChart = new Chart(ctx, {
    type: 'doughnut',
    animation:{
        animateScale:true
    },

    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    },

    data: {
        labels: ["Red", "Remaining"],
        datasets: [{
            data: [90, 10],
            backgroundColor: [
                'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
        }]
    }

});
</script>

** Update **

var dataString="<?php echo rtrim(implode($categoriesTest), ',');  ?>";

var dataObject = JSON.parse(dataString);

document.write(dataString);

var ctx = document.getElementById("myChart");

var myChart = new Chart(ctx, {
    type: 'doughnut',
    animation:{
        animateScale:true
    },

    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    },

    data: {
        labels: ["Red", "Remaining"],
        datasets: [{
            data: dataObject.categories,
            backgroundColor: [
                'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
        }]
    }

});
PhpDude
  • 1,542
  • 2
  • 18
  • 33
  • if you want to , parse you data to Javascript than it need encode by jsonencode() function – Soni Vimalkumar Nov 16 '16 at 12:36
  • `document.write(dataString);` - what's that for, I wonder? Other than that, you'd better use `json_encode()` to create a serialized value for JS to use. – raina77ow Nov 16 '16 at 12:36
  • @raina77ow that breaks the code? – PhpDude Nov 16 '16 at 12:38
  • `SELECT COUNT(*)` dont give you an result with a field called `category`, very buggy stuff here. – JustOnUnderMillions Nov 16 '16 at 12:38
  • @JustOnUnderMillions Yes it does give me the correct result, it counts the categories and then grouping then adds them together. – PhpDude Nov 16 '16 at 12:39
  • OK, but is see, never used `count(*) countname` that way before or better the name category get me stuck:) better use categoryCount for better reading, But `GROUP BY category` makes no sense there. You will get only one result: the count of all categorys. – JustOnUnderMillions Nov 16 '16 at 12:43
  • Test it: `SELECT category, COUNT(*) as categoryCount FROM users GROUP BY category` Or how do you now how many counts a category has from that query you build? – JustOnUnderMillions Nov 16 '16 at 12:45
  • it does work, it counts the categories and then outputs the categories and tells me how many of each category there is. – PhpDude Nov 16 '16 at 13:38

1 Answers1

1

json_encode function is good for that. Any php array you can transfer to json and then echo in the js.

var dataString="<?php echo json_encode($categoriesTest);  ?>";
Bhavik Shah
  • 2,300
  • 1
  • 17
  • 32
  • And then what do I do with the variables where I need to use it as the values for `data: []` – PhpDude Nov 16 '16 at 12:38
  • var dataObject = JSON.parse(dataString); in dataObject you will have your data from the categories and use them in the chart initialization like that: dataset: [{data: dataObject.categories}] –  Nov 16 '16 at 12:55
  • Im still mega confused here.. So I tried to follow what you said but it just kills the code. `Uncaught SyntaxError: Unexpected token , in JSON at position 1` – PhpDude Nov 16 '16 at 13:40
  • Can you provide the html output of the page. –  Nov 16 '16 at 13:46
  • In the object it outputs it as `data: dataObject.categories,` also see my code above for an update – PhpDude Nov 16 '16 at 13:48
  • Did you try to replace it with –  Nov 16 '16 at 13:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/128266/discussion-between-dan-and-user2693928). – PhpDude Nov 16 '16 at 13:53
  • Yeah but it just seems to kill it all and also there seems to be a syntax error too - could you edit the answer for me just to make sure im not doing this wrong? Like with what I have put together what I am meant to put where...? – PhpDude Nov 16 '16 at 13:54