Select data based on value of ID - php

I am trying to select data based on a value, I have a form which selects data from a table of teams, I need to to get the ID of that row from the select dropdown (which I can do) but then use that to determine the data that it needs to select when im doing an AJAX request. Here goes:
Teams page - This page draws my graph which pulls in data via AJAX to draw the graph and its values:
<form action="teams.php?dashboard_id=<?php echo $dashboard_id; ?>" method="POST">
<select name="teamId">
<option selected="true" disabled="disabled">Please choose...</option>
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboard_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value=' . $row["team_id"] . '>' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="compare">View</button>
</form>
<?php
if (!empty($_POST["teamId"])) {
$teamSelect = $_POST["teamId"];
echo $teamSelect;
}else{
echo "";
}
?>
<div style="max-width: 450px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
Here is the PHP page that im doing the SELECT on:
<?php
include 'config.php';
$teamID = $_POST['teamId'];
$query = sprintf("SELECT
tm.member_id,
tm.team_id,
m.member_id,
m.firstName,
m.lastName,
m.score_1,
m.score_2,
m.score_3,
m.score_4,
m.score_5,
m.score_6,
m.score_7,
m.score_8,
m.dashboard_id,
t.team_id,
t.team_name,
t.dashboard_id
FROM team_members tm
JOIN members AS m
on m.member_id = tm.member_id
JOIN teams AS t
on t.team_id = tm.team_id
WHERE tm.team_id = '$teamID'"); // This need to be dynamic and got from the POST request on the form above.
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
header('Content-type: application/json');
print json_encode($data);
?>
Im drawing the graph out via another file:
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
]};
var ctx = $("#mycanvas");
var config = {
type: 'radar',
data: chartata,
animationEasing: 'linear',
options: {
legend: {
display: true,
position: 'bottom'
},
tooltips: {
enabled: true
},
scale: {
ticks: {
fontSize: 15,
beginAtZero: true,
stepSize: 1
}
}
},
},
LineGraph = new Chart(ctx, config);
var colorArray = [
["#7149a5", false],
["#58b7e0", false],
["#36bfbf", false],
["#69bd45", false],
["#5481B1", false],
["#6168AC", false]
];
for (var i in data) {
tmpscore=[];
tmpscore.push(data[i].score_1);
tmpscore.push(data[i].score_2);
tmpscore.push(data[i].score_3);
tmpscore.push(data[i].score_4);
tmpscore.push(data[i].score_5);
tmpscore.push(data[i].score_6);
tmpscore.push(data[i].score_7);
tmpscore.push(data[i].score_8);
var color, done = false;
while (!done) {
var test = colorArray[parseInt(Math.random() * 6)];
if (!test[1]) {
color = test[0];
colorArray[colorArray.indexOf(test)][1] = true;
done = !done;
}
}
newDataset = {
label: data[i].firstName+' '+data[i].lastName,
borderColor: color,
backgroundColor: "rgba(0,0,0,0)",
data: tmpscore,
};
config.data.datasets.push(newDataset);
}
LineGraph.update();
},
});
});
This is all great but in my select query I need the WHERE clause to show me data determined on the value of the team ID and not a static value but im not sure how to pass across the ID from the select back to the AJAX file?

Use sessions then. $_SESSION['teamID'] = $teamID. Then you can reference it anywhere. Be sure to start the session at the top of each php file using sessions.
session_start();
$teamID = $_POST['teamId'];
$_SESSION['teamID'] = $teamID;
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/book.session.php

Related

How can use SQL query to get values from DB in arrays for a line chart

I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}

how to retrieve data from the selected years

Help me how to post value years form drop-down then it will load into JSON data using ajax. Fix my code please i am a student that love to learn more. I appreciate your contribution to check my code if it is wrong. I'm not familiar with ajax but I'm trying.
<script>
$(document).ready(function () {
getGraph();
function getGraph()
{
$.getJSON("bar_graph_query.php", function (result)
{
var chart = new CanvasJS.Chart("chartBar", {
animationEnabled: true,
theme: "light2",
title:{
text: "Summary Rent Profit"
},
axisY: {
title: "Total (RM)"
},
data: [{
dataPoints: result,
}]
});
chart.render();
});
}
$.("#years").onchange(function(){
getGraph();
});
});
</script>
Scripts ajax load data to json (bar_graph_summary.php)
<div class="label">Select Name:</div>
<select class="form-control" name="years" id="years" style="width: 120px" >
<option value="'">Select Years</option>
<?php
include('db_conn.php');
$query = $conn->query("SELECT YEAR(rent_date) as years FROM rent GROUP BY YEAR(rent_date)");
while($row = $query->fetch_assoc())
{
echo '<option value="'.$row['years'].'">'.$row['years'].'</option>';
}
?>
</select>
Dropdown to select years (bar_graph_summary.php)
<?php
include('db_conn.php');
$data_points = array();
$years = $_REQUEST['years'];
$query = mysqli_query($conn, "SELECT MONTHNAME(rent_date) as month, SUM(rent_total)as total FROM rent WHERE YEAR(rent_date)='$years' GROUP BY MONTH(rent_date)");
//$query = mysqli_query($conn, "SELECT MONTHNAME(rent_date) as month, SUM(rent_total)as total FROM rent GROUP BY MONTH(rent_date)");
while($row = mysqli_fetch_array($query))
{
$point = array("label" => $row['month'] , "y" => $row['total']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
?>
query data json (bar_graph_query.php)

Unable to display x-axis labels on multi-column mysql array in Highcharts

I have a mysql database containing multiple columns of power values captured over time, with time captured in the first column. I would like to plot the power values and display the time of day on the x-axis of a Highcharts chart. I am currently able to display the multiple Power values on the y-axis but I am unable to get the time of day to display on the chart. Here is the PHP code that partially works:
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Can someone tell me how to change the code to pass the values from the time of day column properly?
Here is what the chart currently looks like:
When I made changes to the PHP to add the 'Energy_Date' field to the array passed to Highcharts (shown below) it results in a blank chart.
The array consists of fields that look like this (a time stamp followed by a power reading, separated by period:
"2018-02-21 16:56:00.052","2018-02-21 16:59:00.052","2018-02-21 17:02:00.039","2018-02-21 17:05:00.039","2018-02-21 17:08:00.039"
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_Date'].$tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Energy_Date'].$tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Energy_Date'].$tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The html receiving this array looks like this:
<!DOCTYPE html>
<html lang="en">
<title>Combined Values Graph</title>
<head>
<meta http-equiv="refresh" content="180">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var x_values = [];
var chart;
$(document).ready(function() {
Highcharts.setOptions({
colors: ['#4083e9', '#99ccff', '#00ffff', '#e6e6e6', '#DDDF00', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$.getJSON("values.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'mygraph',
type : 'spline',
borderWidth: 1,
zoomType: 'x',
panning: true,
panKey: 'shift',
plotShadow: false,
marginTop: 100,
height: 500,
plotBackgroundImage: 'gradient.jpg'
},
plotOptions: {
series: {
fillOpacity: 1
}
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
title: {
text: 'Combined Power Readings'
},
subtitle: {
text: 'Total = Neurio + Solar Readings in Watts'
},
xAxis : {
title : {
text : 'Time of Day'
}
},
yAxis: {
title: {
text: 'Power (watts)'
},
plotLines: [{
value: 0,
width: 2,
color: '#ff0000',
zIndex:4,
dashStyle: 'ShortDot'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 120,
borderWidth: 1
},
plotOptions : {
spline : {
marker : {
radius : 0,
lineColor : '#666666',
lineWidth : 0
}
}
},
series: json
});
});
});
});
</script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div class="container" style="margin-top:20px">
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-body">
<div id ="mygraph"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I have added the console statement to the bottom of the js like so:
series: json
});
console.log(json);
});
Here's what is shown in the browser console for PHP version 1 (The version that displays the graphs).
Browser console 1
Here's what is shown in the browser console for PHP version 2 (The version that gives a blank chart).
Browser console 2
Thanks for your helpful suggestions. I have changed the while loops to look like this:
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
The output of the PHP now looks like this:
[{"name":"Total_watts","data":[1519315164,93,1519315344,354]},{"name":"Neurio_watts","data":[1519315164,76,1519315344,309]},{"name":"Solar_watts","data":[1519315164,17,1519315344,45]}]
The data being passed to Highcharts (from the console) now looks like this:
Browser console 3
The chart is still wrong: the x-axis is not showing the timestamps and the chart is incorrect. Can anyone suggest how to change the PHP or html to correct this?
OK, I have updated the while loops to look like this:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
The PHP output now looks like this:
[{"name":"Total_watts","data":[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514]...
and the chart is now displaying UTC timestamps for each power value.
You are writing a large block of code with many duplicated components. I've taken the time to DRY your method. It is best practice to minimize calls to the database, so I've managed to combine your queries into one simple select.
Theoretically, you will only need to modify $colnames_labels to modify your HighChart. I have written inline comments to help you to understand what my snippet does. I have written some basic error checks to help you to debug if anything fails.
Code: (untested)
$colnames_labels=[
'Total_watts'=>'Total_watts',
'Power_watts'=>'Neurio_watts',
'Solar_watts'=>'Solar_watts'
];
$select_clause_ext=''; // declare as empty string to allow concatenation
foreach($colnames_labels as $colname=>$label){
$data[]=['name'=>$label]; // pre-populate final array with name values
// generates: [0=>['name'=>'Total_watts'],1=>['name'=>'Neurio_watts'],2=>['Solar_watts']]
$select_clause_ext.=",$colname";
// generates: ",Total_watts,Power_watts,Solar_watts"
}
$subarray_indexes=array_flip(array_keys($colnames_label)); // this will route resultset data to the correct subarray
// generates: ['Total_watts'=>0,'Power_watts'=>1,'Solar_watts'=>2]
if(!$result=mysqli_query($con,"SELECT UNIX_TIMESTAMP(Energy_Date) AS Stamp{$select_clause_ext} FROM combined_readings ORDER BY Energy_Date")){
$data=[['name'=>'Syntax Error (query error)','data'=>[0,0]]; // overwrite data with error message & maintain expected format
}elseif(!mysqli_num_rows($result)){
$data=[['name'=>'Logic Error (no rows)','data'=>[0,0]];
}else{
while($row=mysqli_fetch_assoc($result)){
foreach($subarray_indexes as $i=>$col){
$data[$i]['data'][]=[$row['Stamp'],$row[$col]]; // store [stamp,watts] data in appropriate subarrays
}
}
}
echo json_encode($data,JSON_NUMERIC_CHECK); // Convert to json (while encoding numeric strings as numbers) and print to screen

jquery sortable saving to database not working properly

I'm trying to incorporate the jquery sortable functionality into my website and saving the positions in the database is giving me all sorts of headaches... I've been fighting this for 3 days now, and I cannot seem to get this work properly.
As it stands, it is saving positions to the database, but not in the order or positions, that you'd expect. Meaning, if I move the item in position 0 to position 1, it saves the positions in a different order in the db. check out a live version here.
Here is my code...
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js file:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php file:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode( ($arr['sort']) );
Can anyone please point to where I am going wrong on this?
Thank you in advance.
Serge
In case someone lands on here, here is what worked in my case...
NOTE: I did not create prepared statements in the index.php select function. But you probably should.
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<div id='sort_<?php echo $items['id'] ?>' class='items'>
<span>☰</span> <?php echo $items['description'] ?>
</div>
<?php
}
}
?>
</div>
jquery sortable file:
var ul_sortable = $('#container');
ul_sortable.sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = ul_sortable.sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
ul_sortable.disableSelection();
update php file:
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
require_once('conn.php');
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$db->close();
}
Change your JS code like this:
{...}
tolerance: 'pointer',
cursor: 'move',
// new LINE
items: '.items', // <---- this is the new line
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
var post={},count=0;
$(this).children('.items').each(function(){
post[++count]=$(this).attr('id');
});
// new LINES end
$.ajax({
{...}
With this $.each loop you overwrite your var post -> serialize and define your own sort order. Now look at your $_POST["positions"] with PHP print_r($_POST["positions"]); and you have your positions in your own order.

JQWidgets Combobox Typed value not being echoed or submitted to database

Below are the codes I am using,
When I selected values from the Database, they are submitted to the database, but if I type something not in the database and I want it submitted, It does not get submitted or echoed by PHP.
Sombody Please help me.
Thank You.
<?php
//Jason File
#Include the connect.php file
include('db_connect2.php');
//get county of selected district
$query = "SELECT * FROM primary_schools ";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$customers[] = array(
'Emis_No' => $row['Emis_No'],
'District' => $row['District'],
'County' => $row['County'],
'Subcounty' => $row['Subcounty'],
'Parish' => $row['Parish'],
'School' => $row['School']
);
}
echo json_encode($customers);
?>
//Script
<script type=”text/javascript”>
$(document).ready(function () {
//start EMIS code
var customersSourcel =
{
datatype: "json",
datafields: [
{ name: 'Emis_No'},
{ name: 'District'},
{ name: 'County'},
{ name: 'Subcounty'},
{ name: 'Parish'},
{ name: 'School'}
],
url: 'includes/emis.php',
cache: false,
async: false
};
var customersAdapterl = new $.jqx.dataAdapter(customersSourcel);
$("#emis_no").jqxComboBox(
{
source: customersAdapterl,
width: 200,
height: 25,
promptText: "emis",
displayMember: 'Emis_No',
valueMember: 'Emis_No'
});
$("#emis_no").bind('select', function(event)
{
if (event.args)
{
var index = $("#emis_no").jqxComboBox('selectedIndex');
if (index != -1)
{
var record = customersAdapterl.records[index];
document.form1.district.value = record.District;
$("#county").jqxComboBox({ disabled: false});
document.form1.county.value = record.County;
$("#sub_county").jqxComboBox({ disabled: false});
document.form1.sub_county.value = record.Subcounty;
$("#parish").jqxComboBox({ disabled: false});
document.form1.parish.value = record.Parish;
$("#school").jqxComboBox({ disabled: false});
document.form1.school.value = record.School;
}
}
});
Initialize $customers array with $customers = array(); in the begining of the PHP file before you start pushing values into it with $customers[] = ...

Categories