drawing highchart organization chart from MySQL data with PHP - php

I want to dynamically create an organization chart from MySQL data
As this link I have two files data.php and index.php
in the data.php I have read MySQL data and in index.php I have accessed the data from data.php file
following in data.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "highcharts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM org_chart";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$json = [];
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["amount"]. "<br>";
$json[]=[ (string)$row["parent"] , (string)$row["child"]];
}
echo json_encode($json);
} else {
echo "0 results";
}
$conn->close();
?>
following is above php file result
[["meraj","azim"],["meraj","masoma"],["meraj","jamal"],["mraj","zainab"],["azim","ajmal"],
["azim","omid"]]
and following is my index file which is to show the org chart, but it is not showing
any help please
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/sankey.js"></script>
<script src="https://code.highcharts.com/modules/organization.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<style>
.highcharts-figure, .highcharts-data-table table {
min-width: 360px;
max-width: 800px;
margin: 1em auto;
}
.highcharts-data-table table {
font-family: Verdana, sans-serif;
border-collapse: collapse;
border: 1px solid #EBEBEB;
margin: 10px auto;
text-align: center;
width: 100%;
max-width: 500px;
}
</style>
</head>
<body>
<figure class="highcharts-figure">
<div id="container"></div>
</figure>
<script type="text/javascript">
$(document).ready(function () {
var options = {
chart: {
height: 600,
inverted: true
},
title: {
text: 'Highcharts Org Chart'
},
accessibility: {
point: {
descriptionFormatter: function (point) {
var nodeName = point.toNode.name,
nodeId = point.toNode.id,
nodeDesc = nodeName === nodeId ? nodeName : nodeName + ', ' + nodeId,
parentDesc = point.fromNode.id;
return point.index + '. ' + nodeDesc + ', reports to ' + parentDesc + '.';
}
}
},
series: [{
type: 'organization',
data: [],
}],
};
$.getJSON("data.php" , function (data) {
options.series[0].data = data;
var chart = new Highcharts.chart('container', options);
});
});
</script>
</body>
</html>

Related

Date and time wrong on Highstock chart

I have had a look at my chart issue and I think the problem lies in the Highstock code. I have 2 other charts running the same php code and I have only changed from highchart to highstock.
I am trying to add a range selector in my chart. The code for that works in terms of showing the zoom and selector buttons but the date is now showing incorrectly.
I am drawing the data from an online MySQL data base so I its hard to run a demo for you.The timestamp format has worked in my other charts as mentioned.
This first code shows the date correctly
<?php
// 1-test.php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test page 2</h2>
<div id="chart-temperature" class="container"></div>
</div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartT = new Highcharts.Chart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
Then this code shows the date as Thursday,Jan 1, 00:00:00:001
<?php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test Page</h2>
<div id="chart-temperature" class="container"></div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartH = new Highcharts.stockChart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
rangeSelector: {
buttons: [{
type: 'day',
count: 3,
text: '3d'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
selected: 3
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { second: '%H:%M:%S' },
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
the first screen shot is working. The second is the wrong date,
Any thoughts on how to change the date
The difference between the charts results from the fact that the second chart is a stock chart, which doesn't support categories on a x-axis. You need to use data in the [x, y] format.
var value1 = [18.10, 14.5];
var reading_time = ['2021-08-22 15:00:53', '2021-08-23 15:00:53'];
var seriesData = value1.map(function(val, index) {
return [new Date(reading_time[index]).getTime(), val];
});
Live demo: http://jsfiddle.net/BlackLabel/xLh7y8d6/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

how can i limit the number of results fetched and then filter them?

I recently started learning ajax in order to use the live filter by checkbox. This worked out well until i decided to limit the results fetched from the database using order by id asc limit 0,$rowperpage where rowperpage = 3. Adding this to my code disabled the checkbox filter completely. What could i be doing wrong?
The following is my code.
index.php
<?php
//index.php
include('database_connection.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Product filter in php</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<!-- Page Content -->
<div class="">
<h3>Duration</h3>
<?php
$query = "
SELECT DISTINCT(duration) FROM career
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="checkbox">
<label><input type="checkbox" class="common_selector duration" value="<?php echo $row['duration']; ?>" > <?php echo $row['duration']; ?></label>
</div>
<?php
}
?>
</div>
<br />
<div class="filter_data">
</div>
<style>
#loading
{
text-align:center;
background: url('loader.gif') no-repeat center;
height: 150px;
}
.jobs{
background: gray;
margin: 10px;
padding: 10px;
width: 200px;
}
</style>
<script>
$(document).ready(function(){
filter_data();
function filter_data()
//this deals with filter checkboxes
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var duration = get_filter('duration');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, duration:duration},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
});
</script>
</body>
</html>
fetch_data.php
<?php
//fetch_data.php
include('database_connection.php');
$rowperpage = 3;
if(isset($_POST["action"]))
{
//statement limits but disables check box filter
$query = "
SELECT * FROM career order by id asc limit 0,$rowperpage
";
if(isset($_POST["duration"]))
{
$duration_filter = implode("','", $_POST["duration"]);
$query .= "
WHERE duration IN('".$duration_filter."')
";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<div class="jobs">
Title : '. $row['title'] .' <br />
duration : '. $row['duration'] .'
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
database_connection.php
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=biit", "root", "");
?>
The database table 'career'
Any help will be much appreciated :)

Need help styling PHP in HTML

This is my PHP coding from which I am grabbing data from my DB with a select where statement and outputting it. I am trying to change the text properties such as font, colour and size on the print statement can anybody assis with how to do this?
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT fname, sname FROM tbl_stylist WHERE fname = 'liza'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
print " - Name: " . $row["fname"]. " " . $row["sname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
You can style lists using HTML <ul> and <li> elements.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Stylists</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT fname, sname FROM tbl_stylist WHERE fname = 'liza'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<ul>";
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<li>Name: " . $row["fname"]. " " . $row["sname"]. "</li>";
}
echo "</ul>";
} else {
echo "0 results";
}
mysqli_close($conn);
?></body>
</html>
And in css/style.css put something like this:
li {
color: red;
font-weight: bold;
font-size: 12pt;
}
You can also put the style inline in the head section:
<style type="text/css">
li {
color: red;
font-weight: bold;
font-size: 12pt;
}
</style>
You can output your markdown like this:
print "<div class = 'sampleclass'> - Name: " . $row["fname"]. " " .
Then style it by including the below in an attached css file
.sampleclass {
font-size: 15px;
}
This is only about HTML and CSS, you could output directly your strings in HTML tags with echo. The script needs to be encapsulated into the HTML's body and a pre-defined CSS classes for styling:
<!doctype html>
<html>
<head>
....
<style type="text/css">
.redBold {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<?php
....
echo '<span class="redBold">This text is red and bold</span>';
?>
</body>
</html>
Of course you can also use inline styling:
<span style="color: red; font-weight: bold;">Also this works</span>
You can always use CSS file and define the values.
For example:
body {
font-family: arial;
font-size: 15px;
}
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
php txt
</body>
</html>
Also, you can use <span> tags and style them.
For example print this span using 'print' of php:
<span style="font-family: arial; font-size: 15px;">text</span>

Data not loading in HighChart from MYSQL

I have recently started working on Highchart. I dont have indepth knowledge. But I am still trying my level best. I have tried few codes, but I didn't get any results. The browser console is not loading anything and it is showing blank. Can you please help me in pointing out what to do next. I tried my level best. Please me out.
Here is my code:
Database Coding: php.data
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","root","demo") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from project_requests";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
index.php
<!DOCTYPE HTML>
<?php
include_once 'data.php';
?>
<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">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Brands',
colorByPoint: true,
data: [
<?php
//$sql = mysqli_query("select * from project_requests")
while($res=mysql_fetch_array($sql)){
?>
['<?php echo $res['month']; ?>', 45.0],
<?php
}
?>
]
}]
});
});
</script>
</head>
<body>
<script src=
"https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>
MY sql: Database Snapshot
Schema:: Demo Table:: project_requests

Fullcalendar won't enter data from mysql table into the calendar

I am trying get Fullcalendar to take information from a mysql table and enter the informtion into the calendar. The calendar appears, but none of the information from the table is on the calendar.
Here is my code.
calendar.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type='text/css'>
body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#loading {
position: absolute;
top: 5px;
right: 5px;
}
#calendar {
width: 900px;
margin: 0 auto;
}
</style>
<link rel='stylesheet' type='text/css' href='fullcalendar/fullcalendar.css' />
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery/ui.core.js'></script>
<script type='text/javascript' src='jquery/ui.draggable.js'></script>
<script type='text/javascript' src='fullcalendar/fullcalendar.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#calendar').fullCalendar({
editable: true,
events: "json-events.php",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
</script>
</head>
<body>
<div id='loading' style='display:none'>loading...</div>
<div id='calendar'></div>
<p>json_events.php needs to be running in the same directory.</p>
</body>
</html>
json_events.php
<?php
include("dbstuff.inc");
$conn = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());
$sql= "SELECT id, title, description, url, email, Stime, Etime, eventDate, DATE_FORMAT(eventDate, '%Y-%m-%dT%H:%i' ) AS startDate
FROM events
ORDER BY startDate DESC";
$check = mysql_query($sql) or die(mysql_error());
$events = array();
while ($row = mysql_fetch_assoc($check)) {
$eventArray['id'] = $row['id'];
$eventArray['title'] = $row['title'];
$eventArray['description'] = $row['description'];
$eventArray['url'] = $row['url'];
$eventArray['email'] = $row['email'];
$eventArray['startTime'] = $row['Stime'];
$eventArray['EndTime'] = $row['Etime'];
$eventArray['title'] = $row['Stime'] . " " . $row['title'];
$eventArray['start'] = $row['startDate'];
$eventsArray['allDay'] = "";
$events[] = $eventArray;
}
echo json_encode($events);
?>
This is the data from MySQL file
[
{
"id": "1",
"title": "07:00:00 test1",
"description": "werewr",
"url": "http://www.nba.com",
"email": "someone#host.com",
"startTime": "07:00:00",
"EndTime": "09:00:00",
"start": "2013-04-22T00:00"
},
{
"id": "2",
"title": "11:00:00 test2",
"description": "hello",
"url": "http://www.nba.com",
"email": "someone#host.com",
"startTime": "11:00:00",
"EndTime": "13:00:00",
"start": "2013-04-15T00:00"
}
]
you have events: "json-events.php" and your php file it's json_events.php

Categories