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
});
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!
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>
I have a php file names test.php which gives me a JSON output which is a valid output as I have validated in http://jsonlint.com/ .I want to use that JSON directly in my .html code which used D3.
test.php
<?php
$user = "root";
$password = "";
$database = "scheduler";
$con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$query = "SELECT semone.userid AS id, semone.semester AS semester, semone.cname AS name, courses.credit AS value, courses.progskill AS skill
FROM semone
INNER JOIN courses
ON semone.cname = courses.coname" ;
$result = mysqli_query($con,$query)or die ("Unable to connect");
$lastId = null;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['xyz'] = array(
'name'=> $row['name'],
'value'=> $row['value']
);
$info[$row['semester']]['semester'] = $row['semester'];
$info[$row['semester']]['children'][]= $row['xyz'];
$lastId = $row['id'];
}
// do not call json_encode on each iteration of the loop
$data = json_encode(array('id' => $row['id'], 'children' => array_values($info)));
// echo $data;
?>
The html code where I am trying to use the JSON created from test.php in D3.
tree.html
var canvas = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height + padding);
var data;
d3.json("test3.php", function (error,json) {
if(error) return console.warn(error);
data = json;
console.log(data);
var treemap = d3.layout.treemap()
.size([550,550])
.nodes(data);
var cells = canvas.selectAll(".cell")
.data(treemap)
.enter()
.append("g")
.attr("class","cell")
It is not showing anything as if it is not able to access that JSON file. However When I am using the same JSON through some JSON file saved in the folder, it is working fine. So there is some problem in connection of this html and php file.
Uncomment the echo $data . It should work fine.
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");
Using following MySQLi and PHP snippet I can export the result in a numeric array as:
["8","188.396496","7.876766","69885005.45"]
Now I need to have the output in exact numeric format like (removing " " from the items)
[8,188.396496,7.876766,69885005.45]
and here is the code I have in PHP part
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
$json=json_encode($row);
}
}
$con->close();
echo $json;
?>
How can I do that?
Update
var req2 = $.ajax({
type: "POST",
data: data,
dataType: 'json',
url: "assets/tempchart.php"
});
req2.done(function(data) {
var cars = [];
cars.push(data)
console.log(cars[0]);
in this case the out out is [8,188.396496,7.876766,69885005.45] but I need to get ONLY 8 as cars[0] is 8.
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row); // Convert strings to numbers
echo json_encode($row);
}
The Javascript should be:
req2.done(function(data) {
var cars = [];
cars.push(data[0]);
console.log(cars[0]);
});
You just have to cast your results to float before calling json_encode :
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
// Cast to float
foreach($row as &$item) {
$item = (float) $item;
}
$json=json_encode($row);
}
}
$con->close();
echo $json;
(And you are only getting the last row of your table, because you overwrite the content of $json each time but if you only have one row in your table that can be ok)
Please try to use floatval() function to convert string from DB in float values.