Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

lui hurk

Dificuldades com o google chart no php mysql

Recommended Posts

Fiz desta forma claro está errado pode me orientar ?

<?php
$con=mysql_connect("localhost","root","STRONG") or die("Verifique a  conexao!!!!");
mysql_select_db("gestao", $con);
$sth = mysql_query("SELECT * FROM progarmacao");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
 
    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'equipamento', 'type' => 'string'),
    array('label' => 'total', 'type' => 'number')
 
);
 
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['equipamento']); 
 
    // Values of each slice
    $temp[] = array('v' => (int) $r['total']);
    $rows[] = array('c' => $temp);
}
 
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
 
<html>
  <head>
    <!--Load the Ajax API-->
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

            google.load("visualization", "1", {packages: ["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Equipamentos', 'Total'],
<?php



$query = "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento";

$sth = mysqli_query($query) or die(mysqli_error());
$link = mysqli_connect('localhost', 'root', 'STRONG', 'gestao');
$sth = mysqli_query($link, "select * from progarmacao");






while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[1]', $r[3]],\n";
}
?>
                ]);

                var options = {
                    title: 'Sites CE, RN e RS ',
                    is3D: true,
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>
 
  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Obrigado

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ja disse, seu código ta diferente da documentação

olha lá, o da documentação é simples e poucas linhas

 

eu até dei um exemplo que testei

mas obvio que se vc copiar e colar nao vai funcionar, tabela, banco são diferente

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

            google.load("visualization", "1", {packages: ["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Equipamentos', 'Total'],
<?php
$link = mysqli_connect('localhost', 'root', '', 'teste');
$sth = mysqli_query($link, "select * from nomes");
while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[1]', $r[2]],\n";
}
?>
                ]);

                var options = {
                    title: 'My Daily Activities',
                    is3D: true,
                };

                var chart = new google.visualization.PieChart(document.getElementById('wd'));
                chart.draw(data, options);
            }
        </script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Companheiro funcionou a visualização as contagens, só que a análise objeto da orientação ainda não fora alcançada. Agora minha duvida aonde o SUM entra no códio da documentação,...se flui ao vazio por ser estático ou caso ao contrario, se eu precisar do JSON, sei que estamos quase perto do objetivo, mas se formos parar para reinventar a roda voltaremos a estaca (0), estou pescando e você esta me ensinando a pescar não pense que quero o peixe, tento fazer aqui como acho ser lógico e não dando certo peço orientação, só repito forum é onde existem experts no assunto, decidi estar aqui depois de fazer , refazer tudo sozinho por tutorias durante 4 meses, foi aí que percebi que a internet ficou muito pequena pós ter aceito este desafio , então achei que a minha decisão foi inteligente ,

peço se possível esta clarevidência, caso não for possível vamos pra frente.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Onde entra o SUM()?

no select antes do while

$sth = mysqli_query($link, "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento");

O nome da tabela esta certo? progarmação?

Compartilhar este post


Link para o post
Compartilhar em outros sites

É...já... tinha percebido o erro,... você testou aí?... porque, aqui não deu certo, o gráfico não aparece, tentei três formas possíveis porem, em vão.

 

Aplicando esta linha ao código,

O js me retorna assim:

<html>
  <head>
    <!--Load the Ajax API-->
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

            google.load("visualization", "1", {packages: ["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Equipamentos', 'Total'],

<br />
<b>Notice</b>:  Undefined offset: 2 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 3 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
['', ],
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 3 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
['', ],
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 3 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
['', ],
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 3 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
['', ],
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 3 in <b>C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php</b> on line <b>58</b><br />
['', ],
                ]);

                var options = {
                    title: 'Sites CE, RN e RS ',
                    is3D: true,
          width: 500,
          height: 300
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>
 
  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Tá a linha 58 é esta : echo "['$r[2]', $r[3]],\n";

 

Já sem linha do SUM, os valores retornam corretamente.

Compartilhar este post


Link para o post
Compartilhar em outros sites

vc esta usando a funcção mysqli_fetch_assoc?

se sim:

como postei no post #16, para poder acessar com indies numéricos $r[0], $r[1] etc, tem que usar a funcao mysqli_fetch_array OU ainda a mysqli_fetch_row no lugar da mysqli_fetch_assoc

 

Só confirma, o select esta correto ?

SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento

faça direto no banco;

Compartilhar este post


Link para o post
Compartilhar em outros sites

a função mysqli_fetch_assoc?

não

 

a função mysql_fetch_assoc?

 

sim

 

quando eu insiro:

este

mysqli_fetch_assoc

 

me retorna o gráfico e este alert:

 

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, resource given in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 19

 

quando volto com:

 

mysql_fetch_assoc

 

retorna só o gráfico mas daquele mesmo jeito que estamos tentando mudar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ok..pela 3 vez vou escrever isso

 

para poder acessar com indies numéricos $r[0], $r[1] etc, tem que usar a funcao mysqli_fetch_array OU ainda a mysqli_fetch_row no lugar da mysqli_fetch_assoc

 

O mesmo vale se estiver usando a extenção mysql

Compartilhar este post


Link para o post
Compartilhar em outros sites

ok Te envio como fiz conforme dito.

<?php
$con=mysql_connect("localhost","root","STRONG") or die("Verifique a  conexao!!!!");
mysql_select_db("gestao", $con);
$sth = mysql_query("SELECT * FROM progarmacao");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
 
    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'equipamento', 'type' => 'string'),
    array('label' => 'total', 'type' => 'number')
 
);
 
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['equipamento']); 
 
    // Values of each slice
    $temp[] = array('v' => (int) $r['total']);
    $rows[] = array('c' => $temp);
}
 
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
 
<html>
  <head>
    <!--Load the Ajax API-->
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

            google.load("visualization", "1", {packages: ["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Equipamentos', 'Total'],

<?php

$link = mysqli_connect('localhost', 'root', 'STRONG', 'gestao');
$sth = mysqli_query($link, "select * from progarmacao");

//$sth = mysqli_query($link, "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento");
//$sth = mysqli_query($link, "SELECT gestao as equipamento,count(*) as total FROM progarmacao group by equipamento ORDER BY total DESC");


while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[1]', $r[3]],\n";
}
?>
                ]);

                var options = {
                    title: 'Sites CE, RN e RS ',
                    is3D: true,
          width: 350,
          height: 200
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>
 
  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Desta forma fora, qual você orientou dai então não mudou nada.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara pra que tudo isso de código PHP antes de <html>?

 

Veja eu só usei isso de PHP, só isso, mais nada, você esta complicando

<?php
$link = mysqli_connect('localhost', 'root', '', 'teste');
$sth = mysqli_query($link, "select * from nomes");
while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[1]', $r[2]],\n";
}
?>

e outra você comentou a linha do select que traz os resultados agrupados. porque??

não era isso o que você queria?

 

e outra, progarmacao ??

nao seria programacao??

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ok companheiro, desculpe tinha uma programação hoje de madrugada e como estava muito cansado acabei adormecendo, mas companheiro refente a "progarmacao", depois eu corrijo, voce questionou o php antes do <html>

Beleza, veja como ficou deois do "ajuste" e o que retornou.

<?php

$link = mysqli_connect('localhost', 'root', 'STRONG', 'gestao');
$sth = mysqli_query($link, "select * from progarmacao");

$sth = mysqli_query($link, "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento");
//$sth = mysqli_query($link, "SELECT gestao as equipamento,count(*) as total FROM progarmacao group by equipamento ORDER BY total DESC");


while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[1]', $r[3]],\n";
}
?>


<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
         ['Equipamentos', 'Total'],
          
        ]);

        
$flag = true;
$table = array();
$table['cols'] = array(
 
    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'equipamento', 'type' => 'string'),
    array('label' => 'total', 'type' => 'number')
 
);
 
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['equipamento']); 
 
    // Values of each slice
    $temp[] = array('v' => (int) $r['total']);
    $rows[] = array('c' => $temp);
}


 
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

RETORNO:

 

Notice: Undefined offset: 3 in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 11
['42', ],
Notice: Undefined offset: 3 in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 11
['39', ],
Notice: Undefined offset: 3 in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 11
['94', ],
Notice: Undefined offset: 3 in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 11
['22', ],
Notice: Undefined offset: 3 in C:\xampp\htdocs\www\GRAFICOS\graf_SUM\graftest.php on line 11
['65', ],

Houve a soma sem o gráfico.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara leia a mensagem

Undefined offset: 3

vc selecionou

equipamento e sum(total)

0 1 <- nao tem 3

 

mas eu nao entendo pq vc insiste em fazer diferente da documentação

e diferente do exemplo testado que dei

Compartilhar este post


Link para o post
Compartilhar em outros sites

Beleza, o retorno foi este com a documentação:

 

Sem o SUM

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['equipamento', 'total'],
<?php

$link = mysqli_connect('localhost', 'root', 'STRONG', 'gestao');
$sth = mysqli_query($link, "select * from progarmacao");


//$sth = mysqli_query($link, "SELECT gestao as equipamento,count(*) as total FROM progarmacao group by equipamento ORDER BY total DESC");

//$sth = mysqli_query($link, "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento");
while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[2]', $r[3]],\n";
   
}
?>
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

 

Beleza, o retorno foi este com a documentação:

 

Sem o SUM

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['equipamento', 'total'],
<?php

$link = mysqli_connect('localhost', 'root', 'STRONG', 'gestao');
$sth = mysqli_query($link, "select * from progarmacao");


//$sth = mysqli_query($link, "SELECT gestao as equipamento,count(*) as total FROM progarmacao group by equipamento ORDER BY total DESC");

//$sth = mysqli_query($link, "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento");
while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[2]', $r[3]],\n";
   
}
?>
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

O companheiro desculpas na realidade o retorno foi este.

 

e o código é o de cima

FTE.JPG

 

 

 

 

Código e retorno juntos

 

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

parece que você só lê uma linha do que escrevo

ai é dificil ajudar

te pergunto de novo:

porque você comentou a linha com SUM() e GROUP BY DENOVO??

nao é isso que você queria?

Compartilhar este post


Link para o post
Compartilhar em outros sites

É porque o SUM não funciona e o gráfico não aparece, por isso que comentei, não vou enviar uma tela em branco preferi enviar o que quase deu certo.

 

por este código que enviei se voce testar vai entender o que estou dizendo


Bem, estou vendo estamos esticando para ser objetivo eu so preciso que o meu projeto fique desta forma.

 

 

REEEE.jpgsó isso.

 

Percebe que nos graficos os equipamentos se repetem e não soma o total.


O js deu certo mas o Gráfico não apareceu.

 

 

Segue JS.

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['equipamento', 'total'],

['42', Religadora],
['39', TC],
['94', TP],
['22', TPC],
['65', TRAFO],
        ]);

       var options = {
          title: 'Programação',
          is3D: true,
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart_3d" style="width: 600px; height: 400px;"></div>
  </body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ja postei o código várias vezes mas parece que você nao entendeu
você só tinha que trocar os dados da conexao e do select
SÓ ISSO !!!

como você não sabe fazer isso o deixar o código com tabela que fiz aqui igual a sua.
Novamente o código usando esta tabela
table.JPG

<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

            google.load("visualization", "1", {packages: ["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Equipamentos', 'Total'],
<?php
$link = mysqli_connect('localhost', 'root', '', 'imaster');
$sth = mysqli_query($link, "SELECT equipamento, sum(total) from tabela group by equipamento");
while ($r = mysqli_fetch_array($sth)) {
    echo "['$r[0]', $r[1]],\n";
}
?>
                ]);
                var options = {
                    title: 'My Daily Activities',
                    is3D: true,
                };
                var chart = new google.visualization.PieChart(document.getElementById('piechart'));
                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <div id="piechart" style="width: 900px; height: 500px;"></div>

    </body>
</html>

Capturar.png

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.