I am using google charts (on a php webpage) with data from an sql DB. The problem i am having is that it is not display the field names and values properly it simply displays the value of the first field "expense". It should be showing two fields "expense" and "income" with the values in the db. Any ideas what i am doing wrong ?
my code below:
<?php
$dbhandle = new mysqli('localhost','root','','useraccounts');
echo $dbhandle->connect_error;
$query = "SELECT * FROM ctincome";
$res = $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
echo "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
var options = {
title: 'Expenses to Income',
pieHole: 0.4,
};
var chart = new
google.visualization.PieChart(document.getElementById
('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
the values for the income column should be numbers, not strings.
remove the single quotes from the second column.
from...
echo "['".$row['expense']."','".$row['income']."'],";
to...
echo "['".$row['expense']."',".$row['income']."],";
I have three suggestions based on my experience in crossbrowser or javascript bugs I solved.
First point : You are just echoing, you need to use concatenation.
<?php
$data = '';
while($row=$res->fetch_assoc())
{
$data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php echo $data; ?>
]);
second point : In javascript last comma may or may not work, its best to not to append comma if it's a last row.
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
if(last row )
$data .= "['".$row['expense']."','".$row['income']."']";
else $data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
third suggestion : check data type of var data before and after the concatenation
Related
I'm trying to implement an import/export per month graph for my website using Google Charts API with a MySQL database. Everything is ok, but I'm looking for a way to show in my chart also the months without imports or exports. Could someone please help me? Here is a screenshot of my graph, as you can see some months missing
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dati = google.visualization.arrayToDataTable([
['Month', 'Imports', 'Exports'],
<?php
$q = "SELECT month(date) AS month, SUM(imports) AS imports, SUM(exports) AS exports FROM table WHERE year(date)=2020 GROUP BY month(date)";
$res_q=mysqli_query($db,$q);
//fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entry = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."],";
echo $entry;
}
?>
]);
var options = {
chart: {
title: 'Imports and Exports',
subtitle: 'Bar chart',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(dati, google.charts.Bar.convertOptions(options));
}
Consider the following:
<?php
$array = array(1,2,3,5,7,11);
for($i=1;$i<=12;$i++){
if(in_array($i,$array)){echo $i.' yes<br>';} else {echo $i.' no<br>';}
}
?>
You can use an additional array that holds your data and that contains all the months:
<?php
// prepare array with default 'empty' data
$entries = []
for ($m = 1; $m <= 12; $m++) {
$entries[$m] = '[]';
}
And then add the existing data to this array by overwriting the default values:
// fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entries[$row['month']] = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."]";
}
// output
echo implode(',', $entries);
I am trying to create a bar chart using google charts and mysqli. But my code is not working when I try to insert php in the googlecharts it is no longer showing up on the webpage.
my code:
<!--GOOGLE CHARTS-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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 corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//PHP
<?php
if(isset($_GET['id'])) {
$ID= 'id';
$childId=$_GET['id'];
$rowId=$_GET['id'];
$chartsql = "SELECT `feis_entered`, `competition_level1`, `dance_name1`, `firstpl_score1`, `2ndpl_score1`, `3rdpl_score1` FROM `mark_cards1` WHERE id = '$rowId'";
$chartres = mysqli_query($con,$chartsql);
$chartrow=mysqli_fetch_array($chartres);
if($chartres){
$compName = '.$chartrow["feis_entered"].';
$compLvl = '.$chartrow["competition_level1"].';
$danceName = '.$chartrow["dance_name1"].';
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
}
}
?>
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Ranking');
data.addColumn('number', 'Score');
data.addRows([
['1st Place', <?php echo $first;?>],
['2nd Place', <?php echo $second;?>],
['3rd Place', <?php echo $third;?>]
]);
var data = google.visualization.arrayToDataTable([
['Element', 'Score', { role: 'style' }],
[ '1st Place', <?php echo $first;?>, 'color: #91b224',],
[ '2nd Place', <?php echo $second;?>, 'color: #91b224',],
[ '3rd Place', <?php echo $third;?>, 'color: #91b224',],
]);
// Set chart options
var options = {title:'<?php echo $compName - $compLvl - $danceName;?>',
colors: ['#91b224'],
is3D:true,
width:600,
height:550};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
first place, second place, and third place are the fields. CompName, compLvl, and danceName are the title.
EDIT picture of source code below
the chart values should be numbers instead of strings...
try removing the quotes...
from...
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
to...
$first = $chartrow["firstpl_score1"];
$second = $chartrow["2ndpl_score1"];
$third = $chartrow["3rdpl_score1"];
I have the following Google Charts code and I'm trying to connect it with MySQL, I have tried each and everything with it available on the internet but it still shows just one entry of SQL result set, although I have 10 entries in it. On the internet I found the $row_num counter thing and since including it in my code, I have been able to query one entry but I want to query all entries with it. Please help me with this and let me know what mistake (if any) I have been making, Following is my PHP code:
[<?php
``$dbhandle= new mysqli('localhost','root','8317','record');
//echo $dbhandle->connect_error();
$query= "SELECT * from download_manager";
$res= $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':\['bar'\]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable(\[
\['Title', 'No. of Downloads'\],
<?php
$total_rows = mysqli_num_rows($res);
$row_num = 0;
if (mysqli_num_rows($res) > 0) {
while($row=$res->fetch_assoc())
{
$row_num++;
if ($row_num == $total_rows){
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\]";
}
}
}
else
{
echo "0 results";
}
?>
\]);
var options = {
width: 800,
chart: {
'title': 'Top 10 Downloads',
subtitle: 'for the last month'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
See Also : Downloads in the Last 7 Years <br> <br>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>][1]
You have missed adding a comma , in your PHP data loop. Try with the following:
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\],";
i am using PHP and MYSQL in order to retrieve data from the database. i need to embed Google Map and plot markers based on the retrieved data from the MYSQL database.
i am able to retrieve data from the database and display it on the web page as an XML format. but without displaying the Google Map
where is the error in the code?
i will appreciate any help.
code :
<!DOCTYPE html>
<?php
/*
Template Name: MAP
*/
get_header();
?>
<html>
<head>
<script type='text/javascript' src='jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='jquery-ui-1.8.14.custom.min.js'></script>
<style>
BODY {font-family : Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size : 13px ; }
#map_canvas { width:100%; height: 100%; z-index: 0; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=*******************&callback=initMap">
</script>
<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("encodedString").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[2], addressDetails[3]);
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
global $wpdb;
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
//Now we do a simple query to the database
$sql = $wpdb->get_results("select * from site_coordinates", ARRAY_N);
//Multiple rows are returned
foreach ($sql as $row)
{
//This is to keep an empty first or last line from forming, when the string is split
// if ( $x == 0 )
// {
// $separator = "";
//}
//else
//{
//Each row in the database is separated in the string by four *'s
$separator = "****";
//}
//Saving to the String, each variable is separated by three &'s
$encodedString = $encodedString.$separator.
"<p class='content'><b>Site ID :</b> ".$row[0].
"<br><b>Lat:</b> ".$row[1].
"<br><b>Long: </b>".$row[2].
"<br><b>Height: </b>".$row[3].
"<br><b>TX-Power: </b>".$row[4].
"<br><b>TX-Center: </b>".$row[5].
"<br><b>RX-Center: </b>".$row[6].
"<br><b>Coverage Area: </b>".$row[7].
"</p>";
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
</body>
<?php
get_footer();
?>
</html>
using echo json_encode($row);
inside the foraeach loop
this was the result :
You seem to be creating an HTML string from your DB in the PHP. Try creating the data that the googlemap JS is expecting to see, you could do this as a JSON object, easy enough to do in the PHP. Stop trying to display the DB data in HTML, instead think in JSON.
inside your foreach, try this for a start:
echo json_encode($row);
this should start to give you an idea.
then look here:
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
I think this is a case of me not knowing javascript, but I can't for the love of god get this to work
For some reason, creating vars cancels out my java alert code. (maybe bc its wrong)
And my java vars aren't being set correctly.
I pointed out the problems in my comments
In my SQL, I have Temperatures all with an associative value disk 'id'.
So my data structure in this is:
$array[id];
$array[id]=array();
//For every new element
//Using while ($row = mysql_fetch_assoc($result))
$array[id][]="temperature";
//second id
$array[id2];
$array[id2]=array();
//For every new element
$array[id2][]="temperature";
$array[id2][]="temperature2";
$array[id2][]="temperature3";
$array[id2][]="temperature4";
MY ATTEMPT (WRONG CODE):
//I simplified this code down. In my own version, the join works ONLY when I use an actual index "174" instead of a javascript variable that is 174. Couldnt get join to be alerted in this simplified version
<?php
$phparray=array();
$phparray["100"]="First Element";
$phparray["101"]="Second Element";
$phparray["102"]="Third Element";
$phparray["100"]=array();
$phparray["101"]=array();
$phparray["100"][]="First Element - Sub 2";
$phparray["100"][]="First Element - Sub 3";
$phparray["101"][]="Second Element - Sub 2";
echo $phparray["100"]; //Does not show 'First Element'. Shows Array
echo $phparray["100"][0]; //Correctly shows sub element
//var_dump($phparray);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Associative Array in PHP used in Java Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var index=100;
//var index2=<?php echo $phparray[index]; ?>; //Supposed to output 'First Element'
var joined=[<?php echo join($phparray[index], ', '); ?>]; //Supposed to join elements of '100'
alert("hello"); //This line does not work anymore after the var index2 made above
</script>
</head>
<body>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
EDIT: Here is the long full code of my php page:
<?php
include_once("../../config.php");
$conn=mysql_connect($dbhost,$dbuser,$dbpasswd) or die ('Error connecting to mysql');
mysql_select_db($dbname);
ini_set('error_reporting', E_ALL);
//ini_set('display_errors',1);
ini_set('log_errors',1);
$sql = "select disk_id from disk";
$result = mysql_query($sql);
$ids = array();
$names=array();
$temperatures = array();
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row['disk_id'];
$temperatures[]=$row['disk_id'];
//echo "<br>".$row['disk_id'];
}
//
foreach ($ids as $value)
{
//echo "--START ".$value."--<br>";
$sql = "select * from disk_data WHERE disk_id=".$value;
$result = mysql_query($sql);
$dates=array();
$key = array_search($value, $temperatures);
$temperatures[$value] = array();
//var_dump($temperatures);
while ($row = mysql_fetch_assoc($result))
{
$temps = $row['Temperature'];
$temp = explode("||", $temps);
$prehex=$temp[3];
$posthex=hexdec(substr($prehex,-2));
$predate=$row['create_date'];
$postdate =strtotime($predate)*1000;
$output="[".$postdate.", ".$posthex."]";
//$temperatures[$key][] = $output;
$temperatures[$value][] = $output;
$dates[]=$row['create_date'];
//echo $row['create_date']." ".end($temperatures[$key])."<br>";
}
}
print_r(array_keys($array));
var_dump($temperatures);
foreach ($ids as $value)
{
//echo $value;
$key = array_search($value, $temperatures);
//echo "Key: $key; Value: $temperatures[$value]<br />\n";
$comma = join($temperatures[$value],", ");
echo $comma;
echo "\n";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
//names=[<?php echo join($ids, ', '); ?>],
names=["174"], //Above code works. BUT only using ID 174 to test
values=[<?php echo join($temperatures["174"], ', '); ?>], //Supposed to be ALL data. But temp 174
colors = Highcharts.getOptions().colors;
//alert(values);
$.each(names, function(i, name2) {
//alert(seriesOptions.length);
alert(name2.toString()); //Works....
var values=[<?php
echo join($temperatures[name2], ', '); ?>]; //Doesnt work
//alert(values);
console.log(values);
//document.write(values);
seriesOptions[i] =
{
name: name2,
data:values
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length)
{
createChart();
}
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 0
},
title: {
text: 'Test Performance Data',
style: {
margin: '10px 100px 0 0' // center it
}
},
yAxis: {
title: {text:'Temperature (°C)'},
labels: {
formatter: function() {
return this.value + '';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
line: {
gapSize: 0
},
series: {
//compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
yDecimals: 2
},
series: seriesOptions
});
}
});
</script>
</head>
<body>
<script type="text/javascript" src="../js/highstock.js"></script>
<script type="text/javascript" src="../js/themes/gray.js"></script>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
You cannot mix PHP and JavaScript like that. JavaScript variables are not parsed in PHP.
Even when index is replaced by a variable $index or 100, your code would still miss quotes.
Use the following instead:
<script type="text/javascript">
var index=100;
var array = <?php echo json_encode($phparray); ?>;
var joined = array[index];
The last line outputs the following:
var joined={"100":["First Element - Sub 2","First Element - Sub 3"],"101":["Second Element - Sub 2"],"102":"Third Element"};
Before trying this, make sure that you remove the invalid comment in the line after var index = 100;. Otherwise, a PHP warning can be generated, which invalidates the code:
var index=100;
//var index2=PHP Notice: Use of undefined constant index - assumed 'index' in /tmp/t.php on line 29
PHP Notice: Undefined index: index in /tmp/t.php on line 29
Look at the generated code in the client browser, you'll find that it looks like this:
var joined = [First Element - Sub2, Second Element etc.....]
note the lack of quotes around your inserted strings. You've created Javascript syntax errors, which kills the entire <script> block those variables are embedded within.
As Rob W mentions above, you have to use json_encode() to produce VALID javascript out of your arbitrary text.
As a general rule, if you've got PHP generating anything javascript, and especially when filling in variables like that, use json_encode() - it'll keep these kinds of headaches away.
PHP runs server side and will output its content in to the webpage, before its then rendered in your browser and the JavaScript is run. (meaning when php is running, it has no idea what "index" is because as far as its concerned its never been defined.
I expect what you want to do is move your PHP in to javascript so you can then access it however you like in the page. In your JavaScript just add somthing along the lines of this:
var my_array_in_js = <?php echo json_encode($phparray); ?>;
Which will result in PHP printing its array as json, which can then be read by javascript however you want. Then to read a specific index just use
alert(my_array_in_js[index]);