I have the following code which produces this:
If you look at my code, I'm actually trying to rendor 2 charts, and put them on separate table rows so they will be one on top of the other. That's why there are the table lines bunched up around the bottom of the graph. When I delete all the code for my first graph, my second graph shows up on the webpage, but if it is there it does not show up. Is there something I am missing?
I was thinking that maybe I had to include the line: dbhandle->close after each graph, but that wouldn't make much sense since it is just the connection to my MySQL database.
<?php
include("includes/fusioncharts.php");
// variables declared 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" />
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
$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" => "Scrap by Department",
"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"]
)
);
}
$jsonEncodedData = json_encode($arrData);
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
}
$strQuery2 = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = 'NW' GROUP BY ScrapDate ORDER BY ScrapDate";
// Execute the query, or else return the error message.
$result2 = $dbhandle->query($strQuery2) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result2) {
// The `$arrData` array holds the chart attributes and data
$arrData2 = array(
"chart" => array(
"caption" => "By Week",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData2["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result2)) {
array_push($arrData2["data"], array(
"label" => $row["ScrapDate"],
"value" => $row["Quantity"],
//"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData2 = json_encode($arrData2);
$columnChart2 = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
// Render the chart
$columnChart2->render();
// Close the database connection
$dbhandle->close();
}
?>
<table border='1'>
<tr>
<td>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</td>
</tr>
<tr>
<td>
<div id="chart-2"><!-- Fusion Charts will also be rendered here--></div>
</td>
</tr>
</table>
</body>
</html>
SOLVED:
I looked up the constructor for the FusionCharts object, and the 2nd parameter is a unique identifier for the chart. Since I copy and pasted before, I did not think to change it. I set it to chart 2 and now both charts render properly.
This is what it used to be:
$columnChart2 = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
This is the updated code:
$columnChart2 = new FusionCharts("column2D", "mySecondChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
Related
I have this so far :
if (is_request_var('requestor') == 'PPA'){
$dataJson[][] = array("status" => "success","value" => $fetchValue ,"postcode" => $fetchPostCode,"params"=>"");
$notice = $dataJson;
}
I want to get (refer below) from PHP how do i arrange my PHP array code
jQuery191013316784294951245_1485527378760([
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e KENYATTA AVENUE, GENERAL POST OFFICE, 00100",
"postcode": "00100"
},
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e HAILE SALASSIE AVENUE, CITY SQUARE, QLD, 00200",
"postcode": "00200"
}
])
Try this:
$dataJson = array("value" => $fetchValue, "postcode" => $fetchPostCode);
$notice = json_encode($dataJson);
echo $notice;
Returns a string containing the JSON representation of value.
http://php.net/manual/en/function.json-encode.php
I'm trying to get data from my database into a chart. The charts i'm using are from fusioncharts. If i print the row_cnt's they give me the correct information but in the table it gives me the wrong/no information.
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
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>
<script src="includes/fusioncharts.js"></script>
<script src="includes/fusioncharts.charts.js"></script>
</head>
<body>
<?php
$result = $dbhandle->query("SELECT * FROM email");
$result2 = $dbhandle->query("SELECT * FROM email WHERE status='1'");
$result3 = $dbhandle->query("SELECT * FROM email WHERE status='0'");
$row_cnt = $result->num_rows;
$row_cnt2 = $result2->num_rows;
$row_cnt3 = $result3->num_rows;
// If the query returns a valid response, prepare the JSON strin
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
"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" => 'active emails',
"value" => $row_cnt,
)
);
}
row_cnt gives me the total amount of emails
row_cnt2 gives me the total active emails
row_cnt3 gives me the total inactive/signedoff emails
in the chart it only gives me the total registered emails (row_cnt) and when i want to try to add the other 2 in the chart its not giving me any information. The bar with the total registered emails is also display twice. Someone know what im doing wrong or how to do this?
I want to display 3 different bars 1 needs to be the total registered emails bar number 2 needs to be the active ones and bar number 3 the inactive ones.
I think, you should simply push the three values $row_cnt, $row_cnt2 and $row_cht3 one after another.
Look at this:
// The `$arrData` array holds the chart attributes and data
// First, add the chart array that describes the chart itself.
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
...
...
"showAlternateHGridColor" => "0"
)
);
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we add the values each by each as they are available in three single variables.
// 1. Total:
array_push($arrData["data"], array(
"label" => 'total emails',
"value" => $row_cnt
));
// 2. Active:
array_push($arrData["data"], array(
"label" => 'active emails',
"value" => $row_cnt2
));
// 3. Active:
array_push($arrData["data"], array(
"label" => 'inactive emails',
"value" => $row_cnt3
));
But maybe you need to loop, as the number of processed values couldĀ change and you need to be flexible. In that case I recommend to collect the values in a separate array first and then loop the separate array. Like this:
...
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we for an array first and are able to loop over it.
$myBarArray = array();
// 1. Total:
$myBarArray[] = array(
"label" => 'total emails',
"value" => $row_cnt
);
// 2. Active:
$myBarArray[] = array(
"label" => 'active emails',
"value" => $row_cnt2
);
// 3. Active:
$myBarArray[] = array(
"label" => 'inactive emails',
"value" => $row_cnt3
);
// Now we can loop this array, or pass it to a further function or whatever:
foreach ($myBarArray as $bar) {
$arrData["data"][] = $bar;
}
Either way, iterating over $result as in your question does not seem to be the right way.
Also please note the syntax with [] instead of array_push(), which sometimes is more readable.
Hope this helps :-)
I am trying to convert an array obtained by the code below using non-deprecated techniques with php pdo:
$stm = $conn->prepare("SELECT * FROM mysqltable");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
to the following format required for fusioncharts to be used
[
{
label: "CJ Anderson",
value: "25"
},
{
label: "Imran Tahir",
value: "25"
},
...
...
]
The original array is as follows:
Array (
[0] => Array (
[Id] => 6
[Number] => 1234567890
[Visits] => 1
[Name] => John
)
[1] => Array (
[Id] => 7
[Number] => 1236549871
[Visits] => 9
[Name] => Jerry
)
[2] => Array (
[Id] => 8
[Number] => 2147483647
[Visits] => 3
[Name] => Jane
)
)
Any help would be appreciated, thanks.
EDIT:
As I commented below. I have a full php file that works if you put data in manually. I can't get it to work though when I put the $jsonEncodedData in though. Thoughts?
<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/js/fusioncharts.js"></script>
</head>
<body>
<?php
try {
# MySQL with PDO_MYSQL
$mysql_host = 'host';
$mysql_database = 'table';
$mysql_username = 'user';
$mysql_password = 'pass';
$conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Form the SQL query that returns the top 10 most populous countries
// Execute the query, or else return the error message.
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": //$jsonEncodedData}'); <---I tried to insert this after "data":but no results unlike if you put raw data**
[
{
"label":"Bakersfield Central",
"value":"880000"
},
{
"label":"Garden Groove harbour",
"value":"730000"
},
{
"label":"Los Angeles Topanga",
"value":"590000"
},
{
"label":"Compton-Rancho Dom",
"value":"520000"
},
{
"label":"Daly City Serramonte",
"value":"330000"
}
]
}');
// Render the chart
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
==============Edit 12/28/15==========
Tried the following code with no results, Question I have is shouldn't we end in "}" as they require that:
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData);
//}';
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I wanted to post the array differences as well between the "manual" method and the "fetch method (above in this edit).
With fetch:
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": >[{"label":"John","value":"125"},{"label":"Jerry","value":"125"},{"label":"Jane","value":"125"}] ) [constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
With Manual Method (that works):
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": [ { >"label":"Bakersfield Central", "value":"880000" }, { "label":"Garden Groove >harbour", "value":"730000" }, { "label":"Los Angeles Topanga", >"value":"590000" }, { "label":"Compton-Rancho Dom", "value":"520000" }, { >"label":"Daly City Serramonte", "value":"330000" } ] } ) >[constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
I see two differences offhand, the manual inserts spaces around "data" and the ending } parameter.
There is an automatic (and much much easier) way of doing this:
$stm = $conn->prepare('SELECT Name AS label, Visits AS value FROM mysqltable;');
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
$jsonEncodedData = json_encode($results);
echo $jsonEncodedData;
Output (locally tested):
[{"label":"Foo","value":"5"},{"label":"Bar","value":"15"}]
That way you can just use it like this:
$columnChart = new FusionCharts('...
...
"data": ' . $jsonEncodedData . '}');
Note the . '}' in the end.
Before Edit:
You could do something like this:
// This part is just for running purposes
$foo = array (
0 => Array (
'Id' => 6,
'Number' => 1234567890,
'Visits' => 1,
'Name' => 'John'
),
1 => array (
'Id' => 7,
'Number' => 1236549871,
'Visits' => 9,
'Name' => 'Jerry'
),
2 => array (
'Id' => 8,
'Number' => 2147483647,
'Visits' => "3", // Example to output quoted
'Name' => 'Jane'
)
);
$bar = array();
foreach($foo as $k => $v){
$bar[] = array('label' => $foo[$k]['Name'], 'value' => $foo[$k]['Visits']);
}
echo json_encode($bar);
Output:
[{"label":"John","value":1},{"label":"Jerry","value":9},{"label":"Jane","value":"3"}]
Compare with yours (from question) in one line:
[{label: "CJ Anderson",value: "25"},{label: "Imran Tahir",value: "25"},...]
Note: I assumed that value is represented by Visit and label by Name.
Read more about json_encode.
As a summary this is the piece that solved the issue including FirstOne's foreach statement:
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
//print_r($jsonEncodedData);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData . '}');
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
Thanks for everyone's help in solving the issue.
I'm currently taking the results of a table and using wp_send_json to using it as a JSON response. The data is encoded as expected, however I'd like to tweak the output a bit by changing the keys, formating, and order. I'm not sure how to rebuild the array and encode as json after so I'm looking for a little bit of help.
$stuff= $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_table"), ARRAY_A);
wp_send_json($stuff);
As of now the results I get via print_r look as follows.
Array(
[0] => Array(
[id] => 1[gender] => Male[email] => test#loas . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
) [1] => Array(
[id] => 2[gender] => Female[email] => femal#test . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
)
)
When encoded I get:
[{
"id": "1",
"gender": "Male",
"email": "test#loas.com",
"lat": "45",
"long": "-76",
"country_srt": "USA",
"country_long": "United States"
}, {
"id": "2",
"gender": "Female",
"email": "femal#test.com",
"lat": "98",
"long": "-34",
"country_srt": "USA",
"country_long": "United States"
}]
Thing is, I don't really need some of these values and also need to format some things to output for easy map plotting. For instance the country longform and gender go into an html formatted string. What I'm looking to do is transform this array to result in:
[ idhere: {
"value": "1",
"latitude": "45",
"longitude": "-76",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}, idhere: {
"value": "2",
"latitude": "98",
"longitude": "-34",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}]
I think what you need to do is break down the process down into steps (so you can change the data around) instead of sending your sql data to json directly.
build your own array
iterate over your sql result set while adding your own markup
send the output to json
something like:
$preJSON = array();
// select only columns you need
$sql = "SELECT id, gender, country_srt, lat, long
FROM wp_table"
$count = 0; // this is for $preJSON[] index
foreach( $wpdb->get_results( $sql ) as $key => $row ) {
// each column in your row will now be accessible like this:
// $my_column = $row->column_name;
// now we can do:
$value = $row->id;
$latitude = $row->lat;
$longitude = $row->long;
$gender = $row->gender;
$country = $row->country_srt;
$tooltip = array(
"content" => "HTML and stuff" . $gender . "more HTML and stuff" . $country
);
// now we can build a row of this information in our master array
$preJSON[$count] = array(
"value" => $value,
"latitude" => $latitude,
"longitude" => $longitude,
"tooltip" => $tooltip
);
// increment the index
++$count;
}
// after foreach
// send the whole array to json
$json = json_encode( $preJSON );
I believe this should be the basic gist of what you need
CakePHP API returns result like this:
{
"status": "OK",
"themes": [
{
"Theme": {
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
}
]
}
I would like to ask, how can in remove nested Theme object to get result like this?:
{
"status": "OK",
"themes": [
{
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
]
}
Here is my CakePHP code:
$this->Theme->recursive = -1;
// GET USER ID
$themeData['user_id'] = $isSessionValid;
// GET ALL THEMES RELATED TO USER
$foundThemes = $this->Theme->find('all', array(
'conditions' => array(
'Theme.user_id' => $themeData['user_id'])
)
);
$themes = array();
// FOREACH THEMES AND GET COUNT FOR CARDS FOR EACH THEME
foreach($foundThemes as $foundTheme) {
// GET COUNT OF QUESTIONS FOR ACTUAL THEME
$countOfCards = $this->Theme->Card->find('count', array(
'conditions' => array(
'Card.theme_id' => $foundTheme['Theme']['id'])
)
);
// APPEND TO ACTUAL ARRAY
$foundTheme['Theme']['count_of_cards'] = $countOfCards;
array_push($themes,$foundTheme);
}
// SET SUCCESS RESPOSNSE
$this->set(array(
'status' => 'OK',
'themes' => $themes,
'_serialize' => array(
'status',
'themes',
)
));
Many thanks for any advice.
You can manipulate CakePHP's array formats using its built in Hash utility: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash
What I would do would be to flatten the results:
$results = Hash::flatten($results);
Your data array will end up as a single dimensional array looking like this:
$results = array(
'status' => 'OK'
'themes.0.Theme.id' => 20,
...
'themes.1.Theme.id' => 21,
...
);
You can then use string replace to remove "Theme" from your keys:
$keys = array_keys($results);
$keys = str_replace('Theme.', '', $keys);
Then you can use Hash::expand to get your original array, now formatted how you want:
$results = Hash::expand(array_combine($keys, array_values($results)));
I dont think CakePHP supports this. if you want to do this with an easy way check the Set Utility.
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html