Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal estou com uma dificuldade imensa de elaborar um gráfico conectado a BD peguei um código aqui utilisei porem e não aparece depois de ter inserido os dados do DB, alguém pode analisa e ver o que estou fazendo de errado?
<?php
$conectar = mysql_connect('localhost', 'root', 'STRONG');
mysql_select_db('obras', $conectar);
$QtdeRespostas1 = mysql_result(mysql_query("SELECT COUNT( * ) FROM ipotese WHERE info LIKE ('Sim%')"),0);
$QtdeRespostas2 = mysql_result(mysql_query("SELECT COUNT( * ) FROM ipotese WHERE info LIKE ('Não%')"),0);
$QtdeRespostas3 = mysql_result(mysql_query("SELECT COUNT( * ) FROM ipotese WHERE info LIKE ('Não Sei%')"),0);
$QtdeRespostas4 = mysql_result(mysql_query("SELECT COUNT( * ) FROM ipotese WHERE info LIKE ('Em Parte%')"),0);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Sim <?php echo $QtdeRespostas1; ?>'],
['Não <?php echo $QtdeRespostas2; ?>'],
['Não sei <?php echo $QtdeRespostas3; ?>'],
['Em parte <?php echo $QtdeRespostas4; ?>']
]);
// Set chart options
var options = {'title':'1) PergunraI',
'is3D': true,
'width':900,
'height':450};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>Te respondendo a ajuda: não apareceu, apareceu numeros zero, mas vamos ao que realmente quero e não estou conseguindo.
O exemplo abaixo é meu projeto, porém se observar existem tipos repetidos : o que quero é que a quande dos tipos se somam-se por um método "COUNT" ou "SUM" ou outro que possa fazer isto
/applications/core/interface/imageproxy/imageproxy.php?img=https://ia902702.us.archive.org/25/items/grafii/graf.JPG&key=79da9d1f833143fe14137d1fe351285e3b32a9976f053fcf64c763cac9964ed8" alt="graf.JPG" />
E como solicitado a estrutura do meu DB.
/applications/core/interface/imageproxy/imageproxy.php?img=https://ia902600.us.archive.org/24/items/table_593/table.JPG&key=b2def16f92054a9f96aa337965a977436995ac9adf8f266f4fc3363c0825b595" alt="table.JPG" />
Eu acho que você entendeu a cada quantidade que insiro no equipamento ele recupera o total.
Deste jeito NO GRAFICO.
Total Religadora = 42
Total TC = 39
Total TP = 94
Total TPC = 22
Total TRAFO = 20
Ressaltando que no meu formulário a coluna equipamentos é uma combobox.
Sou novo em php e achei o máximo para web.
alem do SUM() vai precisar do GROUP BY no seu select
inclusive este que você me propõe esta aqui:
Total Religadora = 42
Total TC = 39
Total TP = 94
Total TPC = 22
Total TRAFO = 20
Ele funciona muito bem na tabela, porem não sei como por o metodo para o grafico gráfico analisar, tentei foi muito algumas formas e nada por isso a minha visita ao forum especializado em php.
la vai o codigo que me retornou o resultado acima:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "eeee") or die(mysql_error());
mysql_select_db("gestao") or die(mysql_error());
$query = "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['equipamento']. " = ". $row['SUM(total)'];
echo "<br />";
}
?>
ta valendo
Dei uma olhada na documentação
https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart
a modelo é assim;
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Equipamentos', 'Total'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
use o loop para por seus dados
O processo da documentação to ligado, inclusive te envio como desenvolvi o grafico la de cima:
segue para análise:
<?php
require_once('../graf_SUM/conect.php');
$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="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ' WindFarms no 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>
O lance principal é que está repetindo os equipamento e não soma a quantidade dos mesmos eu só preciso desta solução, que não repita os equipamentos e somem (+) as quantidades como o** SUM() GROUP BY select **faz.
Eu não estou sabendo onde o método vai no código ou como vai.
Tenho certeza que agora você entendeu.
Seu select esta funcionando direto no banco? nessa linha //echo $jsonTable; o esta certo os dados que mostra?
eu tentaria assim:
antes desse trecho faz o select e atribua a $sth
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Equipamentos', 'Total'],
<?php
while($r = mysql_fetch_assoc($sth)){
echo "['$r[0]', '$r[1]']";
};
?>
]);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>Não deu certo o gráfico não aparece.
Se copiou e colou, acho que nao ia mesmo
nessa linha vc poe o ID da sua DIV
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
se ainda assim nao aparecer, veja que erro aparece no console
Companheiro é este o retorno
/applications/core/interface/imageproxy/imageproxy.php?img=https://ia902602.us.archive.org/14/items/RESULT_452/RESULT.JPG&key=54201bba70adf9210c104deab34d0910f39c8a71970cc3222b86f04e0a117f1f" alt="RESULT.JPG" />
Estou começando a ficar frustrado.
Aperte CTRL+U pra ver se o codigo JS gerado esta certo
veja o exemplo da documentacao
https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart#3D
Aparentemente o js não está funcionando , como resolver, tentei inserir dados e mesmo assim o js não funciona.
/applications/core/interface/imageproxy/imageproxy.php?img=https://ia601406.us.archive.org/13/items/fruit_953/RESULT.JPG&key=307215a1babd3da42f6bcdfff3c6495ea58d716dfe5d9f01b143042142f9b3ed" alt="RESULT.JPG" />
Companheiro acredito que seu código tenha algum erro de sintax,
Porque, o código a seguir é do meu projeto original aqule chart lá de cima.
segue o js dele.
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable({
"cols":[
{"label":"equipamento","type":"string"},
{"label":"total","type":"number"}],
"rows":[
{"c":[{"v":"TRAFO"},
{"v":20}]},{"c":[{"v":"TP"},
{"v":4}]},{"c":[{"v":"TP"},
{"v":90}]},{"c":[{"v":"Religadora"},
{"v":33}]},{"c":[{"v":"TC"},
{"v":35}]},{"c":[{"v":"TC"},
{"v":4}]},{"c":[{"v":"TPC"},
{"v":22}]},{"c":[{"v":"RELIGADORA"},
{"v":9}]}]});
var options = {
title: ' WindFarms no 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>Olá pessoal estou tentando o método COUNT... alguém poderia analisar por gentileza.
A estrutura do BD continua a mesma, não fugindo do foco.
Acho que é no trecho da Consulta SQL é que estou errando.
<?php
require_once 'GetGraf/confinect.php';
$con = new conexao();
$con->connect();
//Consulta SQL
$query = mysql_query("SELECT gestao as equipamento,
count(*) as total
FROM progarmacao
group by equipamento
ORDER BY total DESC");
$table = array();
$rows = array();
$flag = true;
$table['cols'] = array(
array('label' => 'equipamento', 'type' => 'string'),
array('label' => 'total', 'type' => 'number')
);
while($row = mysql_fetch_assoc($query)) {
$temp = array();
$temp[] = array('v' => (string) $row['equipamento']);
$temp[] = array('v' => (int) $row['total']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
E... Electronic obrigado pela paciência.
Acabei de testar aqui e funcionou, vi que o código que postei antes tem uns erros mesmo
usei mysqli se vc outro tipo de conexão, terá que adaptar
1- troquei
while($r = mysql_fetch_assoc($sth)){
POR
while ($r = mysqli_fetch_array($sth)) {
//para poder acessar com indies numéricos $r[0] $r[1]
2-
aqui faltou vírgula, e onde é numero não vai aspas
troquei
echo "['$r[0]', '$r[1]']";
POR
echo "['$r[0]', $r[1]],";
ficou assim
<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>
>
Companheiro acredito que seu código tenha algum erro de sintax,
Porque, o código a seguir é do meu projeto original aqule chart lá de cima.
segue o js dele.
Eu fiz como está na documentação:
compare o que está com o seu, o seu esta diferente
https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart#3D
Companheiro na visualização deu muito certo, porém na análise é completamente erronia ele ao invés de contabilizar o total de equipamento ele retorna o ID e assim vira uma escala do ID 123451 até 123458
Ele não retorna estes resultados:
Total Religadora = 42
Total TC = 39
Total TP = 94
Total TPC = 22
Total TRAFO = 20
Tentei fazer alguns ajustes e nada adiantou a legenda aparece os SITEs e contabiliza o ID, só não tentei trocar a primary key, não sei se seria uma boa idéia.
Outra observação utilizei outros tipos de gráficos de barra, caluna e linha e a legenda que aparece é só o total e em escala não aparece EQUIPAMENTO e nem no efeito onmouseover do gráfico.
Mas companheiro vou tentando por aqui, embora agora não estou em casa.
Tá valendo grato de +.
Veja
os números dentro das chaves são o índice da tabela
echo "['$r[1]', $r[2]],\n";
se esta vindo o ID então selecionou o ID e pegou o índice dele
veja seu select e altere
você disse que ta usando count(). Por que?
você não queria agrupar e somar?
"SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento";
aparece só total pq foi assim que vc definiu nessa parte
........count(*) as total
O COUNT deixamos de lado....
Voltando ao foco, companheiro tem razão é que num primeiro momento fiz a inversão dos índices e por isso o ato erronio,
Bem dando continuidade, onde eu ponho o "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento" pra dar certo, por gentileza.
Bem dando continuidade, onde eu ponho o "SELECT equipamento, SUM(total) FROM progarmacao GROUP BY equipamento" pra dar certo, por gentileza.
No exemplo que dei nopost #16 ficou junto o com o JS
coloque onde vc achar melhor.
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
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>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.
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?
É...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.
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;
Fora do javascript, imprima todos os $QtdeRespostas...
Se não aparecer nada, o problema é na sql ou no banco de dados. Seria possível mostrar a estrutura dele?