Gauge Chart Values from Database - javascript

Instead of "value": "11413425.62", how can I change the code to get the data from database phpMyAdmin?
Here's my full code..
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'angulargauge',
renderAt: 'Profit10%',
width: '350',
height: '250',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Total Profit",
"subcaption": "After add value",
"lowerLimit": "0",
"upperLimit": "10000000",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50000",
"code": "#e44a00"
}, {
"minValue": "50000",
"maxValue": "75000",
"code": "#f8bd19"
}, {
"minValue": "75000",
"maxValue": "100000",
"code": "#6baa01"
}]
},
"dials": {
"dial": [{
"value": "11413425.62"
}]
}
}
}
);
fusioncharts.render();
});
</script>
and the data had been extracted using this file "dataCountryGrossMargin.php" with this code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//connect to the server
$connect= mysql_connect("127.0.0.1","root","");
//$conn = new mysqli($servername, $username, $password);
if(!$connect)
{
die('Could not connect: '.mysql_error($connect));
}
//connect to the database
mysql_select_db("fyp",$connect);
$result = mysql_query("SELECT Country, COGS FROM `table 3`");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($connect);
?>
Thank you !

You can use a similar approach to the example offered on the Fusioncharts website:
<?php
/* Include the `fusioncharts.php` file that contains functions to embed the charts. */
include("includes/fusioncharts.php");
/* The following 4 code lines contain the database connection information. Alternatively, you can move these code lines to a separate file and include the file here. You can also modify this code based on your database connection. */
$hostdb = "localhost"; // MySQl host
$userdb = "root"; // MySQL username
$passdb = ""; // MySQL password
$namedb = "fusioncharts_phpsample"; // MySQL database name
// Establish a connection to the database
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Name, Population FROM Country ORDER BY Population DESC LIMIT 10";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Countries",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Name"],
"value" => $row["Population"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>

Related

How do i get updated values from php JSON in canvasJS?

Im stuck at trying to get updated values from the JSON array and plotting it on canvasJS.
Here is my JSON array for sensor 1:
[{
"Date": "2020-01-24 07:35:46",
"sensorValue": 213
}, {
"Date": "2020-01-24 07:35:46",
"sensorValue": 433
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 321
}, {
"Date": "2020-02-10 06:03:36",
"sensorValue": 43
}, {
"Date": "2020-02-12 03:30:57",
"sensorValue": 4321
}]
Below is my index2.php file
the updateChart function doesn't seem to work. Im not sure if this is the right way to do it.
the rationale behind the code: I wish to update the graph every few seconds with updated values retrieved thru php. if there are no updated values, the array should not change. hence the reason behind the for-loop and the date comparison.
<?php
include 'getsensor.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
<?php
getSensor();
?>
var updateInterval = 2000;
var sensor1Data = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var sensor2Data = <?php echo json_encode($json_sensor2, JSON_NUMERIC_CHECK); ?>;
// sensor datapoints
var sensor1 = [], sensor2 = [], sensor3 = [], sensor4 = [], sensor5 = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title: {
text: "Soil Moisture Reading"
},
axisX: {
title: "chart updates every " + updateInterval / 1000 + " secs"
},
axisY:{
includeZero: false
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
verticalAlign: "top",
fontSize: 22,
fontColor: "dimGrey",
itemclick : toggleDataSeries
},
data: [{
type: "line",
name: "Sensor 1",
dataPoints: sensor1
},
{
type: "line",
name: "Sensor 2",
dataPoints: sensor2
}]
});
for(var i = 0; i < sensor1Data.length; i++) {
sensor1.push({
x: new Date(sensor1Data[i].Date),
y: Number(sensor1Data[i].sensorValue)
})
}
for(var i = 0; i < sensor2Data.length; i++) {
sensor2.push({
x: new Date(sensor2Data[i].Date),
y: Number(sensor2Data[i].sensorValue)
})
}
chart.render();
setInterval(function(){updateChart()}, updateInterval);
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
function updateChart() {
// retrieves new data from database. updates and shifts the graph.
<?php
getSensor();
?>
var sensor1DataNew = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
var i = sensor1DataNew.length - 1;
// retrieve the index of the new value
for (i; i > 0; i--){
if (sensor1DataNew[i].Date == sensor1Data[19].Date){
break;
}
}
// pushes the new values to be plotted
for(i; i < sensor1DataNew.length; i++) {
sensor1.push({
x: new Date(sensor1DataNew[i].Date),
y: Number(sensor1DataNew[i].sensorValue)
})
}
if(sensor1.length > 20){
sensor1.shift();
}
chart.render();
}
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
here is my getSensor.php file:
<?php
require_once 'mysqldb.php';
$json_sensor1 = array();
$json_sensor2 = array();
$json_sensor3 = array();
function getSensor(){
global $json_sensor1, $json_sensor2, $json_sensor3;
global $db_host, $db_user, $db_pass, $db_name;
/* start connection */
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
# get/display datetime and sensor value
$sensor1 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 1" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor2 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 2" ORDER BY ID ASC, Date DESC LIMIT 20';
$sensor3 = 'SELECT Date, sensorValue FROM sensor WHERE sensorName = "sensor 3" ORDER BY ID ASC, Date DESC LIMIT 20';
// $sensor3 = 'SELECT Date, sensorName, sensorValue FROM sensor WHERE Date IN (SELECT MAX(Date) FROM sensor WHERE sensorName = "sensor 3") ORDER BY ID ASC, Date DESC';
$json_sensor1 = sqlQuery($conn,$sensor1);
$json_sensor2 = sqlQuery($conn,$sensor2);
$json_sensor3 = sqlQuery($conn,$sensor3);
/* close connection */
mysqli_close($conn);
}
function sqlQuery($conn,$sql_query){
$json_array = array();
if($query = mysqli_query($conn,$sql_query)){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$json_array[] = $row;
}
/* free result set */
mysqli_free_result($query);
}
return $json_array;
}
?>
I can't comment, but I think the problem lies in the way you load the data (or the lack of it).
Basically you are loading the data on the PHP page render once, and that is all.
You need some ajax requests periodically to load the data instead of the PHP echo in the updateChart method. (In the initialization part it is fine)
$.ajax({
type: "GET",
url: 'getSensorData.php',
dataType: "text",
async: false,
success: function(data){
sensor1DataNew = data;
}
});
Something like this might work (with a little jquery)

How do include/call this Javascript file in PHP?

I am writing a PHP script that uses Twitters API's to get a response of tweets in JSON. I am then using the id's in this JSON as parameters in Twitter's widgets.createTweet() function.
The official twitter documentation for this can be found here.
I believe the problem is at the point where I am trying to icnlude the Twitter widgets.js file within my PHP script.
Here is my entire PHP script with my keys and tokens redacted:
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => ""
'oauth_access_token_secret' => ""
'consumer_key' => ""
'consumer_secret' => ""
)
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
$number_tweets = count($string['statuses']);
// THIS IS THE PROBLEM AREA ///////////
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
echo '<script>';
$t = 1;
foreach ($js_array as $js) {
echo $js;
$t++;
}
echo '</script>';
?>
I believe the problem is where I am trying to include the js file from https://platform.twitter.com/widgets.js
It seems to me like everything else here should work. This php file doesn't give me any errors when I try to open it in a browser. I am stuck.
What I'm tyring to do with this code:
make an API call to Twitter and retrieve a set of tweets
use the id's in those tweets to pass
How am I trying to do it:
Using php I have made a successful API call to Twitter with the assistance of an open sourced php library/api wrapper.
store the JSON response in an array, loop through that array getting the tweet id's (attributes for each tweet within the json)
use those id's as parameters for twitter's createTweet function
What my problem is:
I think the problem is, is that my code doesn't know what I mean when I use the twttr.widgets.createTweet() js function because htts://platform.twitter.com/widgets.js is not included properly.
To reiterate, this is where I am trying to include that file:
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
Is that piece included properly? If so, are there other things that pop out as erroneous?
Here is a sample of the JSON response from the twitter API call.
{
"statuses": [
{
"created_at": "Wed May 15 15:13:53 +0000 2019",
"id": 1128679903329542144,
"id_str": "1128679903329542144",
"text": "Araw-gabi nasa isip ka, napapanagip ka kahit sa'n magpunta",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"metadata": {
"iso_language_code": "tl",
"result_type": "recent"
},
"source": "Twitter for Android",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 1016132854999183360,
"id_str": "1016132854999183360",
"name": "L Y S Ađź’›",
"screen_name": "ilysachn",
"location": "Homeđź“Ť",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 97,
"friends_count": 73,
"listed_count": 0,
"created_at": "Mon Jul 09 01:32:06 +0000 2018",
"favourites_count": 624,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 188,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/1016132854999183360/1553425392",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "tl"
},
If you want to know what syntax errors you have in runtime use phpstorm.
I fix errors and now code looks like this
and your script will connect in php file.
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = [
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
];
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {
$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);
} else {
$user = "iagdotme";
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string["errors"][0]["message"]."</em></p>";exit();
}
$number_tweets = count($string['statuses']);
?>
<script sync src='https://platform.twitter.com/widgets.js'></script>
<?php
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
?>

Send Data from Cassandra to DataTables (NoSQL)

Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?

Create drilldown fusion chart on the same page

You will get results on the fusioncharts website if you search up what I asked, but it is not exactly what I am looking for.
I am querying data from a MySQL database, and putting this data into a fusion chart to display on my webpage. I want there to be 2 graphs on the same page, and when you click on one of the datapoints on the parent graph, the child graph will display the "drilled down" graph. How can I do this? As of right now I can press on the parent graph and it will open the child graph on a new webpage. This is the code for the home page with the parent graph. The file is named "dept.php".
<?php
/*Include the `fusioncharts.php` file that contains functions
to embed the charts.
*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined before
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
// Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Department, SUM(Quantity) AS Quantity FROM Scrap GROUP BY Department ORDER BY Department";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Sample Chart",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Department"],
"value" => $row["Quantity"],
"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart. Initialize this object using the FusionCharts PHP class constructor. The constructor is used to initialize
the chart type, chart id, width, height, the div id of the chart container, the data format, and the data source. */
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
And then here is the other page that contains the child graph. The file is named "deptDrillDown.php".
<?php
/* Include the `includes/fusioncharts.php` file that contains functions to embed the charts.*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined earlier
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Get the country code from the GET parameter
$countryCode = $_GET["Department"];
// Form the SQL query that returns the top 10 most populous cities in the selected country
$cityQuery = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = ? GROUP BY ScrapDate ORDER BY ScrapDate";
// Prepare the query statement
$cityPrepStmt = $dbhandle->prepare($cityQuery);
// If there is an error in the statement, exit with an error message
if($cityPrepStmt === false) {
exit("Error while preparing the query to fetch data from City Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$cityPrepStmt->bind_param("s", $countryCode);
// Execute the query
$cityPrepStmt->execute();
// Get the results from the query executed
$cityResult = $cityPrepStmt->get_result();
// If the query returns a valid response, prepare the JSON string
if ($cityResult) {
/* Form the SQL query that will return the country name based on the country code. The result of the above query contains only the country code.
The country name is needed to be rendered as a caption for the chart that shows the 10 most populous cities */
$countryNameQuery = "SELECT ScrapDate FROM Scrap WHERE Department = ?";
// Prepare the query statement
$countryPrepStmt = $dbhandle->prepare($countryNameQuery);
// If there is an error in the statement, exit with an error message
if($countryPrepStmt === false) {
exit("Error while preparing the query to fetch data from Country Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$countryPrepStmt->bind_param("s", $countryCode);
// Execute the query
$countryPrepStmt->execute();
// Bind the country name to the variable `$countryName`
$countryPrepStmt->bind_result($countryName);
// Fetch the result from prepared statement
$countryPrepStmt->fetch();
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Cities in ".$countryName,
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = $cityResult->fetch_array()) {
array_push($arrData["data"], array(
"label" => $row["ScrapDate"],
"value" => $row["Quantity"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is `FusionCharts("type of chart",
"unique chart id", "width of chart", "height of chart", "div id to render the chart", "data format", "data source")`.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
Back
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
n number of charts can be rendered in a single page using FusionCharts.
Store their chart references, e.g. in an associative array.
Use the dataplotClick event to capture the event being generated by clicking on a data.
Inside the callback, use the setJSONData to update the child chart, one wanna update.
A dummy code for this would be:
FusionCharts.ready(function () {
var chart1 = new FusionCharts({
type: 'msstackedcolumn2d',
renderAt: 'chart-container1',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
// enter the json data here
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
/* so every time a dataClickEvent is being triggered from the data plot,
a new json `json2` is fetched from a sql query and
chart2 is updated with it.*/
chart2.setJSONData(json2);
}
}
}
}).render();
});
Couple of days back I created this fiddle, hope this becomes useful here too. Instead of doing a SQL query, here we have a generalised data, every time a click is made, it internally makes a function call, and creates a data dynamically out of it. Lot of function calls for making it entirely dynamic might make the code look complex. But the basic philosophy I shared in the dummy code avobe is the same here.
The snippet version for the code for a quick reference.Better to run the result in full page to check whats exactly happening.
function getData() {
var arr = [{
seriesname: "Book A",
data: [{
"label": "Paper",
"value": 100
}, {
"label": "Promotion",
"value": 150
}, {
"label": "Transportation",
"value": 175
}, {
"label": "Royality",
"value": 200
}, {
"label": "Printing",
"value": 250
}, {
"label": "Binding",
"value": 275
}]
}, {
seriesname: "Book B",
data: [{
"label": "Paper",
"value": 130
}, {
"label": "Promotion",
"value": 110
}, {
"label": "Transportation",
"value": 155
}, {
"label": "Royality",
"value": 250
}, {
"label": "Printing",
"value": 210
}, {
"label": "Binding",
"value": 215
}]
}, {
seriesname: "Book C",
data: [{
"label": "Paper",
"value": 70
}, {
"label": "Promotion",
"value": 180
}, {
"label": "Transportation",
"value": 125
}, {
"label": "Royality",
"value": 150
}, {
"label": "Printing",
"value": 290
}, {
"label": "Binding",
"value": 245
}]
}, {
seriesname: "Book D",
data: [{
"label": "Paper",
"value": 150
}, {
"label": "Promotion",
"value": 100
}, {
"label": "Transportation",
"value": 105
}, {
"label": "Royality",
"value": 125
}, {
"label": "Printing",
"value": 278
}, {
"label": "Binding",
"value": 235
}]
}, {
seriesname: "Book E",
data: [{
"label": "Paper",
"value": 60
}, {
"label": "Promotion",
"value": 250
}, {
"label": "Transportation",
"value": 115
}, {
"label": "Royality",
"value": 189
}, {
"label": "Printing",
"value": 190
}, {
"label": "Binding",
"value": 285
}]
}, {
seriesname: "Book F",
data: [{
"label": "Paper",
"value": 190
}, {
"label": "Promotion",
"value": 200
}, {
"label": "Transportation",
"value": 160
}, {
"label": "Royality",
"value": 148
}, {
"label": "Printing",
"value": 178
}, {
"label": "Binding",
"value": 295
}]
}];
return arr;
}
function getValues(componentName) {
var i,
j,
arr = getData(),
valueArr = [],
len1;
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0, len1 = arr[i].data.length; j < len1; j += 1) {
if (arr[i].data[j].label === componentName) {
valueArr.push({
value: arr[i].data[j].value
});
break;
}
}
}
return [{
seriesname: componentName,
data: valueArr
}];
}
function getProducts(componentName) {
var arr = getData(),
productArr = [];
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0; j < arr[i].data.length; j += 1) {
if (arr[i].data[j].label === componentName) {
productArr.push({
"label": arr[i].seriesname,
"value": arr[i].data[j].value
});
break;
}
}
}
return productArr;
}
function getComponents(label, value) {
var arr = getData(),
sum,
i,
j,
len,
len1,
obj =
componentArr = [];
if (label === undefined) {
label = true;
}
if (value === undefined) {
value = true;
}
for (i = 0, len = arr[0].data.length; i < len; i += 1) {
sum = 0;
obj = {};
for (j = 0, len1 = arr.length; j < len1; j += 1) {
sum += arr[j].data[i].value;
}
if (label) {
obj.label = arr[0].data[i].label;
}
if (value) {
obj.value = sum;
}
componentArr.push(obj);
}
return componentArr;
}
function getSeriesNames() {
var arr = getData(),
seriesName = [];
for (i = 0, len = arr.length; i < len; i += 1) {
seriesName.push({
"label": arr[i].seriesname
});
}
return seriesName;
}
function getMode() {
var e = document.getElementById("interaction");
return e.options[e.selectedIndex].value;
}
FusionCharts.ready(function() {
var lastClickedId = true;
var pieChart = new FusionCharts({
type: 'pie2d',
renderAt: 'pieContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Component-wise BreakUp",
"enableMultiSlicing": "0",
"bgcolor": "FFFFFF",
"showvalues": "1",
"showpercentvalues": "1",
"showborder": "0",
"showplotborder": "0",
"showlegend": "1",
"legendborder": "0",
"legendposition": "bottom",
"enablesmartlabels": "1",
"use3dlighting": "0",
"showshadow": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3",
"palettecolors": "#f8bd19,#e44a00,#008ee4,#33bdda,#6baa01,#583e78"
},
"data": getComponents()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'pie') {
var json = stackedChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
json.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
json.categories[0].category = getSeriesNames();
json.dataset = getValues(dataObj.categoryLabel);
stackedChart.setJSONData(json);
}
}
}
}).render();
var stackedChart = new FusionCharts({
type: 'stackedBar2D',
renderAt: 'barContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"bgcolor": "FFFFFF",
"outcnvbasefontcolor": "666666",
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Product-wise BreakUp",
"xaxisname": "Expenditures Cost",
"yaxisname": "Cost",
"numberprefix": "$",
"showvalues": "0",
"numvdivlines": "10",
"showalternatevgridcolor": "1",
"alternatevgridcolor": "e1f5ff",
"divlinecolor": "e1f5ff",
"vdivlinecolor": "e1f5ff",
"basefontcolor": "666666",
"tooltipbgcolor": "F3F3F3",
"tooltipbordercolor": "666666",
"canvasbordercolor": "666666",
"canvasborderthickness": "1",
"showplotborder": "1",
"plotfillalpha": "80",
"showborder": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3"
},
"categories": [{
"category": getComponents(true, false)
}],
"dataset": getData()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'stackedBar') {
var JSON = pieChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
JSON.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
JSON.data = getProducts(categoryLabel);
pieChart.setJSONData(JSON);
pieChart.slicePlotItem(dataObj.datasetIndex);
}
}
}
}).render();
function resetFN() {
var json = pieChart.getJSONData();
json.chart.subCaption = "Component-wise BreakUp";
json.data = getComponents();
pieChart.setJSONData(json);
json = stackedChart.getJSONData();
json.chart.subCaption = "Product-wise BreakUp";
json.categories[0].category = getComponents(true, false);
json.dataset = getData();
stackedChart.setJSONData(json);
}
document.getElementById('reset').addEventListener('click', resetFN);
document.getElementById('interaction').addEventListener('change', resetFN);
});
h4 {
font-size: 20px;
margin-bottom: 10px
}
.intro {
margin: 0 auto;
background-color: #fff280;
padding: 15px
}
em {
font-style: italic
}
#interactionWrapper {
margin: 5px 10px;
}
button {
border: 1px solid #0b77bc;
background-color: #0d83ce;
color: #ffffff;
margin: 10px 0 0 15px;
padding: 5px 10px;
font-size: 14px;
cursor: pointer
}
.centerAlign {
text-align: center;
}
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<div class="intro">
<h4>Expenditures incurred while publishing books</h4>
<p><em>A company has 6 books to publish for this quater. The stacked chart shows component prices stacked as per different books. While the pie chart, shows the cumilative component price.</em></p>
<p>
<em>There are two interaction modes - namely "Interact in stacked chart" and "Interact in pie chart".On clicking in any plot on stacked chart, it shows the book-wise distribution of that component in the pie chart. Whereas on clicking the pie chart, for a component being clicked, it shows the book-wise distribution in the bar chart</em>
</p>
</div>
<div id="interactionWrapper">
<span>Interaction Mode:</span>
<span>
<select id="interaction">
<option value="stackedBar">Interact in stacked bar</option>
<option value="pie">Interact in the pie chart</option>
</select>
</span>
</div>
<div class="centerAlign">
<span id="barContainer">FusionCharts XT will load here!</span>
<span id="pieContainer">FusionCharts XT will load here!</span>
</div>
<button id="reset">Reset</button>

Rendering complex JSON from mysql and use column value as label

I have a table with 1000 records and a corresponding data history of 5 years, including events. The table structure looks like this at the moment:
id|date|reference_id|account_id|dataSet|price|title|type|description
1|2006-01-03|ID00001|1|dataSet01|44.23|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
2|2006-01-03|ID00002|1|dataSet02|62.75|||
3|2006-01-03|ID00003|1|dataSet03|25.95|Dividend|D|Amount: 0.22
4|2006-01-03|ID00004|2|dataSet04|31.81|||
5|2006-01-03|ID00005|3|dataSet05|78.20|||
6|2006-02-01|ID00001|1|dataSet01|45.85|Dividend|D|Amount: 0.30
7|2006-02-01|ID00002|1|dataSet02|59.37||
8|2006-02-01|ID00003|1|dataSet03|27.59|Dividend|D|Amount: 0.26
9|2006-02-01|ID00004|2|dataSet04|34.24|||
10|2006-02-01|ID00005|3|dataSet05|83.42|||
11|2006-03-01|ID00001|1|dataSet01|45.54|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
12|2006-03-01|ID00002|1|dataSet02|60.86|||
13|2006-03-01|ID00003|1|dataSet03|27.04|Downgrade by Bank from Buy to Hold
14|2006-03-01|ID00004|2|dataSet04|36.04|||
15|2006-03-01|ID00005|3|dataSet05|84.32|||
I want to render the data depending on account_id (in this case account_id = 1) to get the following JSON:
{
"data": [{
"date": "2006-01-03",
"dataSet01": "44.23",
"dataSet02": "62.75",
"dataSet03": "25.95"
}, {
"date": "2006-02-01",
"dataSet01": "45.85",
"dataSet02": "59.37",
"dataSet03": "27.59"
}, {
"date": "2006-03-01",
"dataSet01": "45.54",
"dataSet02": "60.86",
"dataSet03": "27.04"
}],
"events": [{
"dataSet01": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}]
},{
"dataSet03": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Downgrade by Bank from Buy to Hold"
}]
}]
}
I'm struggling to build the json though. As of right now I'm rendering the data like this:
$query = "SELECT date, price
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Obviously this returns the json with price as label for each record value (price). How should the query look like instead to render the above json example?
$query = "SELECT *
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
// Define temporary arrays
$data = array();
$events = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
// Assemble the data grouped by date and dataset
if ( !isset($data[$row['date']]) )
{
$data[$row['date']] = array(
'date' => $row['date'],
);
}
// Inject dataSet in $data grouped by date
if ( !isset($data[$row['date']][$row['dataSet']]) )
{
$data[$row['date']][$row['dataSet']] = $row['price'];
}
// Assemble events grouped by dataSet
if ( !isset($events[$row['dataSet']]) )
{
$events[$row['dataSet']] = array();
}
$events[$row['dataSet']][] = array(
'date' => $row['date'],
'title' => $row['title'],
'text' => $row['type'],
'description' => $row['description']
);
}
// Remove date keys
$data = array_values($data);
return json_encode(array(
'data' => $data,
'events' => $events
));

Categories