Pdo passsa return vaizio in JSON

Asked

Viewed 47 times

1

I am trying to make a cash flow chart with input and output, however, when the JSON value is returning empty. follows below the code

PHP

$ano_hoje = date('Y');

$janeiro_entrada = $conexao->query("SELECT SUM(entrada) AS total FROM caixa where  month(data_trans) ='01' AND YEAR(data_trans)='.$ano_hoje.'");
 while ($row=$janeiro_entrada->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        $json2[]= (int)$row;
 }

JS

new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
    datasets: [{ 
        data: [<?php echo json_encode($json2); ?>],
        label: "Entrada",
        borderColor: "#3e95cd",
        fill: false
      }, { 
        data: [],
        label: "Saída",
        borderColor: "#8e5ea2",
        fill: false
      }, 
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Fechamento mensal referente ao ano atual'
    }
  }
});

HTML

<canvas id="line-chart"></canvas>

1 answer

1

In PHP you can use fetchAll passing by PDO::FETCH_ASSOC to receive an associative array and then encode in json format:

$ano_hoje = date('Y');

$janeiro_entrada = $conexao->query("SELECT SUM(entrada) AS total FROM caixa where  month(data_trans) ='01' AND YEAR(data_trans)='$ano_hoje'");

$data = $janeiro_entrada->fetchAll(PDO::FETCH_ASSOC);

$json = json_encode($data);
  • It worked, but the value is not looking like on the chart. The return value is this [{total:2000}]

  • In the JS of char troque data: [<?php echo json_encode($json2); ?>] for data: <?php echo $json; ?>

  • Yes, I performed this operation. But still the Chart does not show the value

  • It seems that the problem is different, I suggest to open another specific question for this problem. It must be something related to Chart library

  • All right, thanks buddy !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.