php – Graphics in JS , error when inserting data from DB

Question:

I have a huge problem in my hands. I have some graphs in js where I need the data entered in them to come from the database.

But the way the js code is built in, I can't find any way to assign the database data in the graphs. However, it already assigns the database data to other js variables, to make it easier.

Still I'm having difficulties. I hope someone can help me :/

ATTENTION: It is not simply replacing the variables one by one, but making the process automatic, and whenever you add or change a value in the database, the graph will change automatically. I thought about doing a while or for loop, but I don't know how!

Here is how the variables are assigned in the JS of the data coming from the BD :

var row=[];
<?php
$graph=$conn->query("SELECT * FROM lucro")or die("erro");
if($graph->num_rows>0){
    ?>
    var num=<?php echo $graph->num_rows;?>;
      for(var i=0;i<=<?php echo $graph->num_rows; ?>;i++){
        row[i]=[];
      }
    <?php
    $i=0;
    while($row=$graph->fetch_assoc() and $i<=$graph->num_rows){
      $data=date('M',strtotime($row['data']));
      ?>
        row[0][<?php echo $i+1; ?>]="<?php echo $data; ?>";
        row[<?php echo $i; ?>][0]=<?php echo $row['lucro'];?>;

      <?php
    $i++;
    }
}?>
var i=0;

And here we have the code of the graph where I want to swap these variables:

//GRAFICO do lucro p/ANO
 var myConfig = {
  type: "bar",
  plotarea: {
    adjustLayout: true
  },
  scaleX: {
    label: {
      text: "em MILHÕES"
    },

  //AQUI EM BAIXO É ONDE QUERO INSERIR AS VARIAVEIS JS COM OS DADOS DA BD:
    labels: ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug"]
  },
  series: [{

  //AQUI EM BAIXO É ONDE QUERO INSERIR AS VARIAVEIS JS COM OS DADOS DA BD:
    values: [20, 40, 25, 50, 15, 45, 33, 34]
  }]
};

zingchart.render({
  id: 'myChart',
  data: myConfig,
  height: "80%",
  width: "100%"
});

Answer:

You can do it like this:

$labelsJS = array();
$valsJS = array();

while($row=$graph->fetch_assoc() and $i<=$graph->num_rows){
  $data=date('M',strtotime($row['data']));
  ?>
    row[0][<?php echo $i+1; ?>]="<?php echo $data; ?>";
    row[<?php echo $i; ?>][0]=<?php echo $row['lucro'];?>;

    $labelsJS[] = $data;
    $valsJS[] = $row['lucro'];
  <?php
   $i++;
}

$labelsJS = json_encode($labelsJS);
$valsJS = json_encode($valsJS);

Afterwards in js do it, I suppose that here you already see the variable $labelsJS and $datas declared and with the values ​​entered above:

var labels = <?= "JSON.parse('" .$labelsJS. "');"; ?>
var values = <?= "JSON.parse('" .$valsJS. "');"; ?>

//GRAFICO do lucro p/ANO
var myConfig = {
  type: "bar",
  plotarea: {
    adjustLayout: true
  },
  scaleX: {
    label: {
      text: "em MILHÕES"
    },
    labels: labels
  },
  series: [{
    values: values
  }]
};
Scroll to Top