I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>
Related
My goal is to render a graph in PHP using CanvasJS but with multiple datasets dynamically generated based on the values in a DB. Generating this graph with only 1 dataset was working just fine, making it "dynamic" seems to be a challenge.
For 1 dataset I used the code below:
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
Where $dataPoint is send to the JS code
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
type: "line",
dataPoints: <?php echo json_encode($dataPoint, JSON_NUMERIC_CHECK); ?>
}
]
});
chart.render();
});
</script>
So far, so good, so, next step is to extend this to multiple datasets. In this case, for each user in the view "completedgames" we will create a new dataset $datapoint and each $datapoint will be added to the overal dataset $datapoints as shown below:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($dataPoints, $dataPoint);
$dataPoint = array();
}
Where $dataPoints is the value now send to the same JS code as shown in above. Unfortunately this is where it goes wrong. data array_push() function doesn't feel right but I have no idea what the alternative is.
So, I hope this is sufficient information, all information is welcome and thanks in advance!
You have a few different problems, first when appending the data I would do this:
$dataPoint[] = array("x"=> $i , "y"=> $score);
Also I would get rid of this as it seems to be clearing out $dataPoint and might actually be creating additional levels in the array.
array_push($dataPoints, $dataPoint);
$dataPoint = array();
This code creates a $charts variable which looks like the data array in your javascript chart definition, rather than making a representation of just the dataPoints array. That should allow you to have as many data sets as you want.
$charts = [];
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$dataPoint = [];
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($charts, array(
"type" => "line",
"dataPoints" => $dataPoint
));
}
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: <?php echo json_encode($charts, JSON_NUMERIC_CHECK); ?>
});
chart.render();
});
</script>
Using James' input I was able to make my Graph with multiple lines. Just needed to reset the counter and $dataPoint array: here is the working code:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
json_encode($dataPoint, JSON_NUMERIC_CHECK);
$i++;
}
//array_push($dataPoints, $dataPoint);
// $dataPoint = array();
array_push($charts, array("type" => "line", "dataPoints" => $dataPoint));
$dataPoint = array();
$i = 0;
}
Thanks for all your inputs!
Hello everyone I am trying to retrieve some data from data.php then allowing my app.js to display the data via Chartjs.
The data that I want to display is feedbackrowcount & complainrowcount
Which I already did a query to retrieve what I want from mysql.
Below is my data.php that does the query and the json data
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
This is app.js that display the chart. I believe the Data: is the key to not being able to display the chart on my webpage. Please help me to write the statement needed to retrieve data from data.php to app.js. Thank you so much!
$.getJSON('http://localhost/customercare/data.php', function(data) {
console.log(data);
});
var oilCanvas = document.getElementById("oilChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var feedbackvscomplainData = {
labels: [
"Feedback",
"Complain"
],
datasets: [
{
data:
backgroundColor: [
"#FF6384",
"#FF6300"
]
}]
};
var pieChart = new Chart(oilCanvas, {
type: 'pie',
data: feedbackvscomplainData
});
i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.
Heres what i got:
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Meter', 'type' => 'number')
);
$rows = array();
$select->execute();
while ($result = $select->fetch(PDO::FETCH_ASSOC)) {
$timestamp = strtotime($result['date']);
$date = date("d.m.Y - H:i", $timestamp);
$temp = array();
$temp[] = array('v' => $date);
$temp[] = array('v' => $result['meter']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$json = json_encode($table);
echo $json;
?>
<html>
<head>
<script type="text/javascript" src="../assets/js/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
async: true
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
chart.draw(data, {width: 1000, height: 240});
}
</script>
</head>
<body>
<hr class="major" />
<div id="chart_div2"></div>
</body>
</html>
The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file?
When i change async: true to false, it just displays the code from the whole page, with true it displays undefined.
Kind regards,
Skar
when you echo the $json that way
<?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php
// rest of page...
you can use it in javascript later and don't need the ajax anymore.
//....
chart.draw(jsonData, {width: 1000, height: 240});
//....
screen shoot
Hello i have obstacle for my chart from CanvasJs.
I just put simple code to get simple chart with parameter target and actual, i found error in dataPoints: i think the problem just wrong statements.
this my error code:
dataPoints: [
<?PHP $mkmi3= mysql_query("SELECT * FROM monthkpimontindv WHERE idKpiDetIndv='$q'");
While ($mkmi4= mysql_fetch_assoc($mkmi3))
{
echo "{ label: ".$mkmi4['period'].", y: ".$mkmi4['actual']." },\n";
}
?>
]
Here is how we can display MySQL data in CanvasJS, Try like this.
Here, Create a PHP service that returns data in JSON format. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
HTML Page to Fetch Data and render Chart
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Note:: IE8- is supported in v1.3 and above.
I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().