can't make orgchart in php - php

I am trying to make orgchart in my code, a have not any idea about this chart. I want to make a a tree like chart, and want data from mysql table.
Table is : treechart
id name treeid
1 a 1
2 aa 11
3 aaa 111
4 aaaa 1111
5 ab 12
6 aba 121
7 abb 122
8 ac 13
My code is as below :
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
<?php
include get_template_directory()."/connect/connect.php";
$result = mysql_query("select * from treechart order by id asc");
$members = array();
$demo = "[\n";
while ($row = mysql_fetch_array($result))
{
$members[$row[2]] = $row[1];
}
function search_tree($searchkey)
{
return $members[$searchkey];
}
foreach($members as $key=>$member)
{
if(strlen($key)==1)
{
$demo = $demo."['".$member."','','".$member."'],\n";
$one = $member;
}
if(strlen($key)==2)
{
$demo = $demo."['".$member."','".$one."',''],\n";
}
if(substr($key,0,2)=="11")
{
if(strlen($key)==3)
{
$newkey = search_tree("11");
echo $newkey."---.";
}
}
$oldkey = strlen($key);
}
$demo = substr($demo,0,strlen($demo)-2);
$demo = $demo."]";
print_r($newdemo);
?>
data.addRows(<?php echo $demo; ?>);
// 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});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My problem is in $newkey I can't any value, I want the value of 11,12,13 keys value in $newkey. And I have very big amount of data in table, so if anyone have any short coding idea, then help me in my code.

You have to define parent column in your table
id | parrentId | Name
Here is an example
var orgchart = new getOrgChart(document.getElementById("people"),{
dataSource: [
{ id: 1, parentId: null, Name: "1"},
{ id: 2, parentId: 1, Name: "2"},
{ id: 3, parentId: 1, Name: "3"}]
});
html,
body {
margin: 0px;
padding: 0px;
height: 100%;
overflow: hidden;
}
#people {
width: 100%;
height: 100%;
}
<link href="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.css" rel="stylesheet"/>
<script src="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.js"></script>
<div id="people"></div>

Related

Error while fetching MySQL data for Google Charts "Data column(s) for axis #0 cannot be of type string"

The PHP code throws the error "Data column(s) for axis #0 cannot be of type string"
<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([
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>
If I run the code in a separate PHP file
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "['".$row[Year1]."', ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
I get the correct data:
['2003', 0, 207],['2005', 0, 29],['2006', 1, 59],['2007', 1, 148],['2008', 1, 109],['2009', 72, 71],['2010', 450, 261],['2011', 1934, 967],['2012', 662, 206],['2013', 627, 487],['2014', 735, 233],['2015', 720, 350],['2016', 855, 503],['2017', 836, 593],['2018', 983, 950],['2019', 920, 508],['2020', 291, 97],
Where is the error in the code?
the issue is that you're printing "CONNECTED TO CLOUD PRU DATABASE<br>" in the middle of your data array, here...
var data = google.visualization.arrayToDataTable([ // <-- ARRAY STARTS HERE
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
// PRINTING THIS HERE WILL MESS UP YOUR ARRAY
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]); // <-- ARRAY ENDS HERE
but let's back up. first, it is not recommended to manually build json data by concatenating strings and variables.
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
instead, build the array in php and use json_encode to print it on the page.
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
$rows = array();
if ($result->num_rows > 0) {
// add column headings
$rows[] = array('Year1', 'CountGiardiaPos', 'CountCryptoPos');
// output data of each row
while($row = $result->fetch_array()) {
$rows[] = array($row[Year1], $row[CountGiardiaPos], $row[CountCryptoPos]);
}
}
?>
<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() {
// use json_encode to build data table
var data = google.visualization.arrayToDataTable(<?php echo json_encode($rows); ?>);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>

Multi line Google Line Chart, using data from mySQL db

I'm going through a bit of a learning process, in order to create a small database backed reporting system for my company.
The intent is to draw a multi line chart using Google Charts, based on a mysql database.
I've managed to get the data to echo from the mysql database, but it's not generating the chart. All I get is the echo, and a blank space where the chart should be. The echo is shown for debugging purposes.
Here is the code :
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysql_errno($result) .": ". mysql_error($result) ."/n";
die(mysql_error());
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Probe 1', 'type' => 'number'),
array('label' => 'Probe 2', 'type' => 'number'),
array('label' => 'Probe 3', 'type' => 'number'),
array('label' => 'Probe 4', 'type' => 'number')
);
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array($r['time']);
$temp[] = array($r['p1']);
$temp[] = array($r['p2']);
$temp[] = array($r['p3']);
$temp[] = array($r['p4']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?$jsonTable?>);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600
};
var chart = new google.visualization.Table(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
And this is the 'echo' output
{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}
This is test data, using a test query on the db. Once I understand the formatting to render the chart, it will be setup to allow the user to select which date to view, etc.
This was the closest existing question I can find, but doesn't seem to answer the question.
Not able to generate a Google Chart using MySQL table data as the data source
Following the answer of #MickMackusa, I managed to hack this together to get it to work, by ensuring the mysql/php array was output in a manner acceptable to Google Charts.
Thanks to #MickMacUSA for his assistance.
The final, working code, is below.
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
die(mysqli_error());
}
$i = 0; //iteration counter - start at 0
$totalRows = mysqli_num_rows($result); // we need this to know when to change the output
$targetRows = $totalRows - 1; //row indies start from 0, not 1.
foreach ($result as $row){
$comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
if ($targetRows == $i) { // if the index is the same value as the target (ie, it's the last row)...
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
} else {
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
}
$i = $i + 1;
$rows[] = $temp;
}
$table = $rows;
$data = implode($table); //format the table as a single string, with line returns
//echo $i;
//echo $data;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
<?php echo $data; ?> //dump the result into here, as it's correctly formatted
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Your number values must be formatted differently and you want timeofday not datetime.
According to: https://developers.google.com/chart/interactive/docs/reference#dataparam
Format your data to look like this:
{cols:
[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:
[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
}
And you must echo it in the javascript:
change:
<?$jsonTable?>
to:
<?php echo $jsonTable; ?>
And put your javascript code block just before your </body> tag.
This is the full working code using the above data format that I tested on my server:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(
{cols:[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
This is an alternative format that will be simpler/clearer/easier to build/comprehend using your mysqli results:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
[[03,02,07],270.26,298.40,111.54,228.06],
[[03,28,42],273.23,190.43,245.69,283.21],
[[07,26,04],144.33,217.26,206.53,167.68],
[[12,13,20],153.15,277.23,167.20,240.88]
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
See the SO Demo provided by WhiteHat:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = new google.visualization.DataTable({cols: [
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows: [
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var table = new google.visualization.Table(document.getElementById('chart_0'));
table.draw(data);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600,
hAxis: {
format: 'hh:mm:ss'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>

How to iterate database values by date for google charts

I have seen similar questions but still do not understand how it woks.. I have this while loop looping my DB for dates, leads and sold. For each date in the DB I would like to show the daily leads and sold for each date in the DB in a line chart.
$sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sold = $row['sold'];
$visit= $row['visit'];
$date= $row['date'];
}else{
}
}
Here is the chart script -
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChartl);
function drawChartl() {
var data = google.visualization.arrayToDataTable([
['Date', 'Leads', 'Sold'],
['1st', 6, 2],
['2nd', 3, 1],
['3rd', 2, 3],
]);
var options = {
title: 'Internet Performance',
curveType: 'function',
legend: { position: 'top' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 1900px; height: 500px"></div>
see following snippet...
need an array that holds all the data --> $json
then add each row to $json --> $dataRow
then write the result to the javascript --> data.addRows(<?= $jsonstring ?>);
try something like this, probably need to format the date too...
<?php
$json = array();
$sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dataRow = array(
$row['date'],
$row['visit'],
$row['sold']
);
array_push($json, $dataRow);
}
}
$jsonstring = json_encode($json);
?>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'callback': function () {
var data = google.visualization.arrayToDataTable([
[{type: 'string', label: 'Date'}, {type: 'number', label: 'Leads'}, {type: 'number', label: 'Sold'}]
]);
data.addRows(<?= $jsonstring ?>);
var options = {
title: 'Internet Performance',
curveType: 'function',
legend: { position: 'top' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
},
'packages': ['corechart']
});
</script>
<div id="curve_chart" style="width: 1900px; height: 500px"></div>

Google chart for each row of MySqL table

New PHP user here. I have a database that looks like this:
id name day1 day2 day3 day4 day5
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
The database contains thousands of users. Each number in the table represents the amount of daily activities per user. We need a table which looks like this
id name day1 day2 day3 day4 day5 chart
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
We want to draw a google line chart in the last column for each user. This is the code to generate the chart:
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$row = mysqli_fetch_array($result);
$d1=$row['day1']; $d2=$row['day2']; $d3=$row['day3']; $d4=$row['day4']; $d5=$row['day5'];
//// that's the data that get loaded into Google Charts(no axis label) ////
$data="[['','day'],['',".$d1."],['', ".$d2."],['', ".$d3. "],['', ".$d4."],['', ".$d5. "]]";
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width:200,
height:150,
legend: 'none'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<?php echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>charts</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>
<div id=\"chart_div\" style=\"width:200; height:150\"></div></td>";
echo "</tr>";
}
echo "</table>"; ?>
</body>
</html>
This code generates only one chart for user id=2. The first user, and the other users are ignored. How do you get a chart for each row? Thanks four help.
The easiest way requires a bit of rearranging your code to make it work:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(array('', 'Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'));
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[] = array('', $row['day1'], $row['day2'], $row['day3'], $row['day4'], $row['day5']);
$i++;
}
?>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
views.push(new google.visualization.DataView(data));
views[i].setRows([i]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>
That won't produce very nice LineCharts, however, as you will have 5 lines with 1 point each. If you are looking for a single line that spans 5 days, then this is how you want to set it up:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(
array('Day'),
array('Day 1'),
array('Day 2'),
array('Day 3'),
array('Day 4'),
array('Day 5')
);
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[0][] = "Daily activities for {$row['name']}";
$data[1][] = $row['day1'];
$data[2][] = $row['day2'];
$data[3][] = $row['day3'];
$data[4][] = $row['day4'];
$data[5][] = $row['day5'];
$i++;
}
?>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfColumns() - 1; i++) {
views.push(new google.visualization.DataView(data));
views[i].setColumns([0, i + 1]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>

jquery draggable list position save to database

i have following code for get data from database and sort draggable list using jquery ui elements.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; background-color:#CCC;}
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
</script>
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_SESSION['user_id'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '$user_id'");
echo "<ul id='sortable'>";
while($row = mysqli_fetch_array($result))
{
echo "<li class='ui-state-default'>" . $row['Name'] . ' ' . $row['UserName'] . $row['sort'] ."</li>";
}
echo "</ul>";
mysqli_close($con);
?>
This is my database table structure
Table Name = users
Columns = user_id, Name, UserName, Password, sort
Example Results
user_id Name UserName Password sort
1 AAA aa *** 1
2 BBB bb *** 2
3 CCC cc *** 3
4 DDD dd *** 4
what i am asking is, i can Reorder list items by using jquery draggable properties, but how can i save sort number to database if reordered list items.?
jQuery UI sortable has a stop callback which is called when you stop moving a sortable. It also has a serialize function that you can use in combination to send the order of your sortables to your to the process which updates your database. You can use it like this:
To use serialize you need to amend your sortable element in the DOM so that it contains a reference to the user_id. E.g.
<li class="ui-state-default" id="id_<?php echo $row['user_id'] ?>">...</li>
Then when you serialize the sortable, it will build a list of parameters. You don't have to use the id attribute to reference your data, read more about the serialize method here. But below is an example of how you can do it using the id attribute
var $sortable = $( "#sortable" );
$sortable.sortable({
stop: function ( event, ui ) {
// parameters will be a string "id[]=1&id[]=3&id[]=10"...etc
var parameters = $sortable.sortable( "serialize" );
// send new sort data to process
$.post("/sort/my/data.php?"+parameters);
}
});
You then need a process that receives this data and updates the database. I'll leave most of this up to you, but here's a minimal example.
<?php
// Store user IDs in array. E.g. array(0 => "1", 1 => "3", 2 => "10"....)
$userIds = $_POST['id'];
// Connect to your database
$conn = mysqli_connect("localhost","root","","db_name");
foreach ($userIds as $key => $userId) {
$sequence = $key + 1;
$stmt = $conn->prepare("UPDATE users SET sort = $sequence WHERE user_id = ?");
$stmt->bind_param("i", (int) $userId);
$stmt->execute();
}
$stmt->close();

Categories