How to loop in PHP and display all rows - php

So I have this problem in looping in PHP, I can't seem to display, it only displays the first row. I want to display all 18 places and at the same time all places have different counts/data each. I think I'm missing a lot in PHP.
//This part of code displays the names and counts the met conditions
$sql = "SELECT b.name as brgy0,(SELECT COUNT(brgy_id) FROM tbl_fire_info where YEAR(date_of_report)=$year AND MONTH(date_of_report)=$smonth and status=1 AND brgy_id=b.barangayID) as cnt FROM tbl_barangay as b";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$numData = $row['cnt'];
$brgyData = $row['brgy0'];
//This part of code displays the data in the graph, I decided to loop it 18 times
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: ['<?php if(isset($_POST['submit'])){echo $haz;} ?>'],
datasets: [ //barangays
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
{
label: "<?php if(isset($_POST['submit'])){echo $brgyData;} ?>",
backgroundColor: "#3e95cd",
data: [<?php if(isset($_POST['submit'])){echo $numData;} ?>]
}
<?php
echo ",";
}
}else {
echo "0 results";
}
?>
]
},
options: {
title: {
display: true,
text: 'Number of reports'
}
}
});

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;
}
}

Select data based on value of ID

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

How to display data in HIGHCHART from mysql database using datepicker?

have a problem when i choose the start date and end date in datepicker to display the data in highchart, the data in highchart is display alll data..so plaese some body to fix it. thank u
this's my source code
<script>
function dialogbx(){
myDialogBox('9');
}window.addEventListener("load",dialogbx);
</script>
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: 'Type Grafik : Column'
},
xAxis: {
categories: [
<?php
$sql2 = "SELECT * FROM pinjaman WHERE $filterPeriode GROUP BY tgl_pinjam ";
$query2 = mysql_query( $sql2 ) or die(mysql_error());
while($ret2=mysql_fetch_array($query2)){
$tahun = $ret2['tgl_pinjam']; ?>
'Tanggal <?php echo $tahun; ?>',
<?php } ?>
] ,
},
yAxis: {
title: {
text: 'Jumlah Pinjaman (Rupiah) '
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [
<?php
include('../library/inc.connection.php');
$query1=mysql_query("select kd_jenis from pinjaman where $filterPeriode && level ='1' group by kd_jenis");
while($array1=mysql_fetch_array($query1)){
$kdjenis = $array1['kd_jenis'];
?>
{
name: '<?php echo $kdjenis; ?>',
data: [<?php $query3 = mysql_query("select * from pinjaman WHERE $filterPeriode && level ='1' group by tgl_pinjam ");
while($array3 = mysql_fetch_array($query3)){
$query4 = mysql_query("select kd_jenis,SUM(jumlah_pinjam) from pinjaman where kd_jenis='$kdjenis' &&
$filterPeriode && level ='1' group by kd_jenis ");
while( $data = mysql_fetch_array( $query4 ) ){
$jumlah = $data['SUM(jumlah_pinjam)'];
}
echo $jumlah.",";
} ?>]
},
<?php } ?>
]
});
});
</script>

Using jquery highchart with dynamic php values fetched from mysql datatable

I tried finding a well explained example or at least a definition, but had no luck.
So basically I have a data-table, I want to fetch some values from it and display it using jquery high-chart.
So far, I have this:
<?php
include("connect.php"); //script for connecting to database and defining the $connection
$query = "SELECT * FROM meetings";
$result = mysql_query($query, $connection);
$numberOfMeetings = 25; //this is mocked here so you can better understand the code
echo '<table>
<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['memberName'] . '</td>';
echo '<td>' . ($row['timesPresent'] / $numberOfMeetings) * 100 . '%</td>';
echo '</tr>';
}
?>
I get a nice simple table with a lot of rows and 2 columns. First column is showing the name of the member and the second one is showing the percentage how many times he has been present on a meeting.
My question is now that I have this data-table and those values (I can always put the values in arrays if needed) how can I display it like this done on the fiddle: http://jsfiddle.net/uDrQq/3/
I somehow need to pass the categories and the data from php values to the jquery code,but how?
To use this you have to pass DB values from PHP to Javascript
use php on same page or get the values from AJAX
here is the demo how to use on same page
<?php
include("connect.php"); //script for connecting to database and defining the $connection
$query = "SELECT * FROM meetings";
$result = mysql_query($query, $connection);
$numberOfMeetings = 25; //this is mocked here so you can better understand the code
$membername=array();
$timepresent=array();
while ($row = mysql_fetch_array($result)) {
$membername[]=$row['memberName'];
$timepresent[]=($row['timesPresent'] / $numberOfMeetings) * 100;
}
$membername="'".implode("','", $membername)."'";
$timepresent=implode(",", $timepresent);
?>
//pass values in Javascript
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Percentage of members on meetings'
},
xAxis: {
categories: [<?php echo $membername?>],
title: {
text: "Members"
}
},
yAxis: {
min: 0,
title: {
text: 'Percentage',
align: 'middle'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueDecimals: 2,
valueSuffix: ' %'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
credits: {
enabled: false
},
series: [{
name: 'Present: ',
data: [<?php echo $timepresent?>]
}]
});
});

using json with jquery for jtables?

I am using jtables (http://www.jtable.org), but one of the options to create a combobox (dropdown menu) is such:
Branch: {
title: 'Branch',
type: 'list',
options: {
'1': 'Auckland',
'2': 'Queensland'
}
}
I want to be able to use a mysql query (JSON'ed?) for my "options" instead of hardcoding it. Any ideas?
Branch:{
title: 'Page Name',
width: '30%',
options: 'FieldNameLoader.php?action=Branch',
list :true
}
if($_GET["action"] == "Branch") {
$result = mysql_query("SELECT * from tblPagelist ORDER BY PageName ASC;");
$rows = array();
while ($row = mysql_fetch_array($result)) {
$eil = array();
$eil["DisplayText"] = $row[1];
$eil["Value"] = $row[0];
$rows[] = $eil;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult); }
Use PHP's json_encode with mysql_fetch_array
PHP
while($row = mysql_fetch_array($query)) {
$options[$row['id']] = $row['name'];
}
$options = json_encode($options);
JSON
Branch: {
title: 'Branch',
type: 'list',
options: <?=$options?>
}
What I do is on the php side I query everything and put it into an array and then echo it to the javascript page:
Branch: {
title: 'Branch',
type: 'list',
options: <?php echo json_encode($branchArray)?>
}

Categories