Google chart bug when using PDO connection - javascript

I'm trying to use google charts to show my database values. I'm using PDO for my database queries inside a class where I instantiate it as an object on my HTML page inside my PHP tag. However the google chart is not working the way it should be, the piechart title and the names of the values are not showing up.
This is my current output
This is what I want to be shown
my html page:
<?php
$dashboard = new userview; ?>
<!DOCTYPE html>
<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([
['ticketstatus', 'statusnumber'],
<?php
$dashboard->getstatuscount();
?>
]);
var options = {
title: 'Request Status'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</body>
</html>
my query class :
class userview extends dbh{
public function getstatuscount() {
$sql = "SELECT ticketstatus, COUNT(*) as statusnumber FROM ticketpractice GROUP BY ticketstatus";
$result = $this->connect()->query($sql);
while ($row = $result->fetch()) {
echo "['".$row['ticketstatus']."',".$row['statusnumber']."]," ;
}
}
}
my database class
class dbh
{
private $dbhost = "localhost";
private $dbusername = "root";
private $dbpassword = "";
private $dbname = "myphplessons";
protected function connect () {
$dsn = 'mysql:host=' . $this->dbhost . ';dbname=' . $this->dbname;
$pdo = new PDO ($dsn,$this->dbusername, $this->dbpassword);
$pdo->setAttribute (PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}

Related

Dynamic Chart in PHP using Chart js

I am not being able to show the values from my PHP file into my HTML file using Chart js. I am trying to import it through AJAX request. I tried it through printing the database value as JSON in the PHP file. The encoding worked well but I can't show them in graph for some reason. Please suggest any other way if possible to do the task mentioned in the code
HTML:
<html>
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/LineGraph.js" type="text/javascript" ></script>
</head>
<body>
<h1>Chart.js Sample</h1>
<div id= "graphDiv" style="width:100%; height:auto;">
</div>
<script>
showGraph();
function showGraph(){
$.post("agSensorInterfaceUpdate.php", function (data){
console.log(data);
var ctx = $("#graphCanvas");
var acc_data = [];
var gyr_data = [];
var serial = [];
for(var i in data) {
acc_data.push(data[i].accelerometer);
gyr_data.push(data[i].gyroscope);
serial.push(data[i].serial_no);
}
var chartdata = {
labels: serial_no,
datasets: [
{
label: 'Accelerometer Data',
backgroundColor: 'rgba(200,200,0.75)',
borderColor: 'rgba(200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: acc_data
}
]
};
var lineGraph = new Chart(ctx, {
type:'line',
data: chartdata
});
});
}
</script>
</body>
PHP:
<?php
header('Content-Type: application/json');
$username = "root";
$password = "";
$database = "arthor_bb";
$serial=1;
$sensor_value = array();
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM `sensor_data`";
$result = $mysqli->query($query);
foreach ($result as $row){
$sensor_value[] = $row;
}
$result -> close();
print json_encode($sensor_value);
?>
your "graphDiv" html element needs to be a canvas. not a div.
<canvas id="myChart" width="100%" height="50%"></canvas>
You also have the wrong id on your ctx variable.
let ctx = document.getElementById('myChart').getContext('2d'); // canvas

Google chart : Navigating to other page on click of the node link

Hi I am using google organisation charts for my web application in Codeigniter- PHP/Mysql. I have loaded the nodes of my chart from mysql database. And the text in the nodes are made as links. Everything is fine till now. But now I want to add href to the link, so that when user clicks on the link it should navigate to the details page, where the details of particular node is shown. I know, in order to show the details, there should be an Id of the node to fetch the data from database.
So here's my question How can I add this id to the link?
Is there any way to do this? Can anyone please help me. Here is my code:
model:
public function getTreeMembersData()
{
$this->db->select('E1.name AS memname,E2.name AS parentname,E3.name AS spouse');
$this->db->from('tab_members AS E1');
$this->db->join('tab_members AS E2', 'E2.member_id = E1.parent_id','left outer');
$this->db->join('tab_members AS E3', 'E3.parent_id = E1.member_id AND E3.relation_id = 3','left outer');
$this->db->where('E1.relation_id !=', 3);
$query = $this->db->get();
return $query->result();
}
Controller:
public function membertree()
{
if(isset($_SESSION['username']) || isset($_SESSION['userid']))
{
$page['pagename'] = "membertree";
$data['msg'] = $this->session->flashdata('msg');
$this->load->view('header',$page);
$data['treedata'] = $this->Family_model->getTreeMembersData();
$this->load->view('membertree',$data);
$this->load->view('footer');
}
else
{
redirect('Auth/login');
}
}
View:
<script type="text/javascript">
var url="<?php echo base_url();?>";
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
var data;
var chart;
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Parent');
data.addRows([<?php
foreach($treedata as $d)
{
$memname = $d->memname;
$parent = $d->parentname;
$spouse = $d->spouse;
?>
[{v:'<?php echo $memname;?>', f:'<a><?php echo $memname;?><a><div><a><?php echo $spouse;?></a></div>'},'<?php echo $parent; ?>'],
<?php
}
?>]);
var options = {
'width':250,
'height':600};
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if(selectedItem) {
var name = data.getValue(selectedItem.row,0);
alert(name);
}
}
}
<div class="box">
<div class="box-body">
<div id="chart_div" class="chart"></div>
</div>
</div>
if you are able to get the id from the query,
you can add in the address to the details page as a 'GET' parameter in the href attribute.
something like...
<a href="http://address.to/details.php?id=<?php echo $id_field;?>"><?php echo $memname;?><a>
as in the data row...
[{v:'<?php echo $memname;?>', f:'<?php echo $memname;?><a><div><a><?php echo $spouse;?></div>'},'<?php echo $parent; ?>'],

How do I create a C3 Chart Line Graph from JSON data?

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>

HighCharts and PHP json_encode. Data from MySQL. No data on chart

Trying to produce HighCharts with data from MySQL. Parsing data from MySQL using PHP and the json_encode function. Problem: No data on chart.
This is my javascript:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('json.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="max-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
This is my json.php:
<?php
$host = "localhost:3306";
$user = "removed";
$pass = "removed";
$dbname = "removed";
$connection = mysqli_connect($host, $user, $pass, $dbname);
$query = "SELECT temp, time from vejr where time > '2016-04-25 06:14:23'";
$result = mysqli_query($connection, $query);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
?>
This is the output from the json.php:
[{"temp":"1.6","time":"2016-04-25 08:14:23"}, {"temp":"2.6","time":"2016-04-25 09:14:23"},{"temp":"3.6","time":"2016-04-25 10:14:23"},{"temp":"4.6","time":"2016-04-25 11:14:23"}, {"temp":"5.6","time":"2016-04-25 12:14:23"},{"temp":"6.6","time":"2016-04-25 13:14:23"},{"temp":"7.6","time":"2016-04-25 14:14:23"},{"temp":"8.6","time":"2016-04-25 15:14:23"}]
What I'm trying to do is a chart with time (fx 2016-04-25 08:14:23) on the x-axis, and the value (fx 1.6) on the y-axis.
Got inspiration from this: http://www.highcharts.com/docs/working-with-data/custom-preprocessing#3
And also, I know that my timestamp on the x-axis is not perfect, it is long (2016-04-25 08:14:23), but that is what my feeding-software currently is sending to my MySQL. What would be perfect?
Kind Regards
The issue is caused by 3 reasons.
Values should be named like x and y, not custom fields
The y value should be number, not string like you have (use the JSON_NUMERIC_CHECK flag in json_encode)
The x value, should be timestamp (time in miliseconds). In PHP you can use strtotime() function

CanvasJs dynamic Data with PHP, mySQL

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.

Categories

Resources