I have the below syntax that is used to display a MySQL query in PHP:
function get_dayssincecapture($db)
{
$result = $db->query("SELECT DATEDIFF(now(), sarrive)as days,count(loadnumber) as loads from v2loads where adminstatus='captured' group by DATEDIFF(now(), sarrive) ");
return $result;
}
$dayssincecapture = get_dayssincecapture($db);
Display Syntax:
<table border=1>
<tr>
<? while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) { ?>
<td><? echo $row['days']; ?><br><? echo $row['loads']; ?></td>
<? } ?>
</tr>
</table>
this produces the below screen output
How do I alter by table syntax in order to get the days field as a row heading and the load field as the second row of my table?
so what I want will be:
Thanks as always,
Try with:
<?php
$dayssincecapture = get_dayssincecapture($db);
$data = array('days' => array(), 'loads' => array());
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$data['days'][] = $row['days'];
$data['loads'][] = $row['loads'];
}
?>
<table style="border: 1px solid #000">
<tr>
<td>Days</td>
<?php foreach ( $data['days'] as $day ) { ?>
<td><?php echo $day; ?></td>
<?php } ?>
</tr>
<tr>
<td>Loads</td>
<?php foreach ( $data['loads'] as $load ) { ?>
<td><?php echo $load; ?></td>
<?php } ?>
</tr>
</table>
If you wanted to perform this type of transformation in MySQL, then you will be pivoting the data. MySQL does not have a pivot function but you can replicate this using an aggregate function with a CASE statement:
select
count(case when DATEDIFF(now(), sarrive) = 1 then loadnumber end) as Day_1,
count(case when DATEDIFF(now(), sarrive) = 2 then loadnumber end) as Day_2,
count(case when DATEDIFF(now(), sarrive) = 3 then loadnumber end) as Day_3,
count(case when DATEDIFF(now(), sarrive) = 4 then loadnumber end) as Day_4,
count(case when DATEDIFF(now(), sarrive) = 5 then loadnumber end) as Day_5,
count(case when DATEDIFF(now(), sarrive) = 6 then loadnumber end) as Day_6,
count(case when DATEDIFF(now(), sarrive) = 7 then loadnumber end) as Day_7
from v2loads
where adminstatus='captured'
You can also write this code inside of a prepared statement to create this dynamically since the values will be unknown.
You can try:
<?php
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$days_row .= "<td>" . $row['days'] . "</td>";
$loads_row .= "<td>" . $row['loads'] . "</td>";
}
?>
<table>
<tr>
<td>Days</td>
<?php echo $days_row; ?>
</tr>
<tr>
<td>Loads</td>
<?php echo $loads_row; ?>
</tr>
</table>
Related
I am building a leaderboard which is built by joining two different databases, the most important is the wallet column which is what I'll use to rank the players. I need to add a column ranked from the player with most money to least amount of money. What is the best way to do this?
$result = mysqli_query($conn, "SELECT * FROM darkrp_player inner join playerinformation on (darkrp_player.uid = playerinformation.uid)");
Basically, you need to order by on your wallet column to short for showing most money to least amount of money of the user i.e DESC ordering. But if you want to get the rank number value of each user also apart from ordering you can do it this way with ROW_NUMBER() window function
SELECT *, rank FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY wallet DESC) as rank
FROM darkrp_player INNER JOIN playerinformation ON (darkrp_player.uid = playerinformation.uid)
) t
Expected Output: on $result variable
id other........columns wallet rank
1111 xyz............abc 100 1
2222 xyz............abc 90 2
3333 xyz............abc 80 3
alright these work! here's my code for anyone that might across something similar
<table class="table" data-order='[[ 0, "asc" ]]'>
<thead>
<tr>
<th>Place</th>
<th>Avatar</th>
<th>Name</th>
<th>Salary</th>
<th>Wallet</th>
</tr>
</thead>
<tbody>
<?php
$conn = mysqli_connect("bla bla bla");
$result = mysqli_query($conn, "SELECT * FROM darkrp_player inner join playerinformation on (darkrp_player.uid = playerinformation.uid) ORDER BY wallet DESC");
$rank = 1;
while ($row = mysqli_fetch_assoc($result)):
?>
<?php
$steamid2 = $row['steamID'];
$slice = substr($steamid2, strpos($steamid2, ":") + 1);
$n = substr($slice, 0, 1);
$x = substr($slice, strpos($slice, ":") + 1);
$steamid64 = 76561197960265728 + 2 * $x + $n;
$json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=keykeykeykeykeyk&steamids='.$steamid64.'');
$parsed = json_decode($json);
?>
<tr id="rank<?php echo $rank++; ?>">
<td><?php echo $rank - 1; ?></td>
<td><?php foreach($parsed->response->players as $player){
echo "<img src='" . $player->avatarmedium . "'>";
} ?></td>
<td><?php foreach($parsed->response->players as $player){
echo "" . $player->personaname . "";
} ?></td>
<td><?php echo $row['salary']; ?></td>
<td><?php echo $row['wallet']; ?></td>
<?php endwhile; ?>
</tr>
</tbody>
</table>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.6.0/dt-1.13.1/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.6.0/dt-1.13.1/datatables.min.js"></script>
<script>
$(".table").DataTable();
</script>
I am trying to record the attendance of my students that attend my courses. Courses are different lengths and times and I just need to record if a student is (P)resent (L)ate (A)sent. I record the attendance in 1 table and display the records in a pivot table based on the date attended. I am a newby and just can't workout this code to include all the details I need to show. id, bid, fullname, nickname, company_idno, (P)(L)(A).
Please could someone look at my code and tell me how to add this information to the pivot table.
This is what I want to show
This is where I store the information
This is table1
This is table2
At the moment I achieved the look I want but use 2 tables and use CSS to fix the widths of table 1 and place table 2 next to it.
I realize this is terrible practice and of course, I get odd results across different platforms, especially iOS which put a 47px gap between the 2 tables which I can't seem to remove also.
I want just want table 2 to show all the information. I can only show 3 fields, id, date, pla. How to add fullname, nickname and company_idno ??
Table 1
<table id="tblplanames" >
<td id="tdplabc">sid</td>
<td id="tdplabc">bid</td>
<td id="tdplacid" style="text-align: center">Cid</td>
<td id="tdplafn" style="text-align: center">Fullname</td>
<td id="tdplann" style="text-align: center">Nickname</td>
<?php
$sql13="SELECT * FROM students WHERE classno='$id' ORDER BY bluecard_no ASC ";
$sql_row13=mysqli_query($link,$sql13);
while($sql_res13=mysqli_fetch_assoc($sql_row13)) {
$stsid=$sql_res13["id"];
$stidno=$sql_res13["company_idno"];
$stbluecard_no=$sql_res13["bluecard_no"];
$stfullname=$sql_res13["fullname"];
$stnickname=$sql_res13["nickname"];
?>
<tr>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stsid; ?></td>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stbluecard_no; ?></td>
<td id="tdplacid"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stidno; ?></td>
<td id="tdplafn"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stfullname; ?></td>
<td id="tdplann"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stnickname; ?></td>
</tr>
<?php
}
?>
</table>
Table 2
<?php
$id = $_GET['id'];
$sql = "SELECT DISTINCT date
FROM attendance
WHERE classno = $id
ORDER BY DATE";
$res = $link->query($sql); // mysqli query
while ($row = $res->fetch_row()) {
$dates[] = $row[0];
}
/***********************************
* Table headings *
************************************/
$emptyRow = array_fill_keys($dates,'');
// format dates
foreach ($dates as $k=>$v) {
$dates[$k] = date('d-M', strtotime($v));
}
$heads = "<table id='tblpla'>\n";
$heads .= "<tr><td>sid</td><td>" . join('</td><td>', $dates) . "</td></tr>\n";
/***********************************
* Main data *
************************************/
$sql = "SELECT date, sid, pla, bluecard_no
FROM attendance
WHERE classno = $id
ORDER BY bluecard_no";
$res = $link->query($sql);
$sid='';
$tdata = '';
while (list($d, $sn, $s, $bcn) = $res->fetch_row()) {
if ($sid != $sn) {
if ($sid) {
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
}
$rowdata = $emptyRow;
$sid = $sn;
}
$rowdata[$d] = $s;
}
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
$tdata .= "</table\n";
echo $heads;
echo $tdata;
?>
SELECT c.olumns
, y.ou
, a.ctually
, w.ant
FROM students s
JOIN attendance a
ON a.classno = s.classno
WHERE s.classno = :id
ORDER
BY s.bluecard_no ASC
, a.date";
public function get_members_for_attendence()
{
$date = $this->input->post('choose_date');
$sql = 'SELECT a.date, c.member_name,c.member_join_date,c.member_payment_date,c.member_exp_date,c.member_payment_date,c.member_contact, c.member_reg_id,
CASE
WHEN a.status = "absent" THEN "Absent"
WHEN a.status = "present" THEN "Present"
ELSE "Not Taken"
END as attendence_status
FROM member_reg AS c
LEFT JOIN attendence AS a ON a.member_reg_id = c.member_reg_id AND a.date = "'.$date.'"';
$query = $this->db->query($sql);
return $query->result();
}
For CodeIgniter 3
it worked for me
I am generating a data from the database to html table using php.
I want to output with php condition using the student joining date.
I want to run a condition where you take the j.date and anything before should have - and after should have a 'Pay' button which holds the studentid
+---------+------------+-----+-----+------+------+------+-----+
| Student | J.date | Jan | Feb | Mar | Apr | May | ... |
+---------+------------+-----+-----+------+------+------+-----+
| John | 25-03-2018 | 0 | 0 | 2000 | 0 | 1750 | ... |
| Michael | 10-04-2018 | 0 | 0 | 0 | 5000 | 0 | ... |
+---------+------------+-----+-----+------+------+------+-----+
Something like this
+---------+------------+-----+-----+------+------+------+-----+
| Student | J.date | Jan | Feb | Mar | Apr | May | ... |
+---------+------------+-----+-----+------+------+------+-----+
| John | 25-03-2018 | - | - | 2000 | Pay | 1750 | ... |
| Michael | 10-04-2018 | - | - | - | 5000 | Pay | ... |
+---------+------------+-----+-----+------+------+------+-----+
Updated
The query
<?php
$sqlFees = "SELECT
s.student_id, s.firstname, s.lastname,
c.subject, c.standard, (t.month * c.fee) AS coursefee,
SUM(f.paid) AS paid, MIN(f.paiddate) AS studentstartdate,
SUM(CASE WHEN MONTH(f.paiddate) = 1 THEN f.paid ELSE 0 END) AS MJan,
SUM(CASE WHEN MONTH(f.paiddate) = 2 THEN f.paid ELSE 0 END) AS MFeb,
SUM(CASE WHEN MONTH(f.paiddate) = 3 THEN f.paid ELSE 0 END) AS MMar,
SUM(CASE WHEN MONTH(f.paiddate) = 4 THEN f.paid ELSE 0 END) AS MApr,
SUM(CASE WHEN MONTH(f.paiddate) = 5 THEN f.paid ELSE 0 END) AS MMay,
SUM(CASE WHEN MONTH(f.paiddate) = 6 THEN f.paid ELSE 0 END) AS MJun,
SUM(CASE WHEN MONTH(f.paiddate) = 7 THEN f.paid ELSE 0 END) AS MJul,
SUM(CASE WHEN MONTH(f.paiddate) = 8 THEN f.paid ELSE 0 END) AS MAug,
SUM(CASE WHEN MONTH(f.paiddate) = 9 THEN f.paid ELSE 0 END) AS MSep,
SUM(CASE WHEN MONTH(f.paiddate) = 10 THEN f.paid ELSE 0 END) AS MOct,
SUM(CASE WHEN MONTH(f.paiddate) = 11 THEN f.paid ELSE 0 END) AS MNov,
SUM(CASE WHEN MONTH(f.paiddate) = 12 THEN f.paid ELSE 0 END) AS MDec
FROM
fees f
JOIN enrollments e ON f.enrollmentid = e.enrollment_id
LEFT JOIN courses c ON e.courseid = c.course_id
LEFT JOIN students s ON f.studentid = s.student_id
LEFT JOIN terms t ON e.termid = t.term_id
WHERE
f.paiddate BETWEEN '2018-01-01 00:00:00' AND '2018-12-31 23:59:59'
GROUP BY
f.enrollmentid
ORDER BY NOT EXISTS
(SELECT studentid
FROM fees f
WHERE f.enrollmentid = e.enrollment_id
AND MONTH(f.paiddate) = MONTH(CURDATE())
) DESC
";
$resultFees = mysqli_query($con, $sqlFees);
?>
<table border="1" cellpadding="8" style="border-collapse: collapse;">
<thead>
<th>Name</th>
<th>Subject</th>
<th>Jan</th>
<th>Feb</th>
<th>Mar</th>
<th>Apr</th>
<th>May</th>
<th>Jun</th>
<th>Jul</th>
<th>Aug</th>
<th>Sep</th>
<th>Oct</th>
<th>Nov</th>
<th>Dec</th>
<th>Paid so far</th>
<th>Start date</th>
</thead>
<?php while($row = mysqli_fetch_assoc($resultFees)) :
$studentId = $row['student_id'];
$studentFName = $row['firstname'];
$studentLName = $row['lastname'];
$studentFullName = $studentFName.' '.$studentLName;
$subject = $row['subject'];
$standard = $row['standard'];
$paid = $row['paid'];
$courseFee = $row['coursefee'];
$studentStartDate = $row['studentstartdate']; // this is the J.date
$monthJan = $row['MJan'];
$monthFeb = $row['MFeb'];
$monthMar = $row['MMar'];
$monthApr = $row['MApr'];
$monthMay = $row['MMay'];
$monthJun = $row['MJun'];
$monthJul = $row['MJul'];
$monthAug = $row['MAug'];
$monthSep = $row['MSep'];
$monthOct = $row['MOct'];
$monthNov = $row['MNov'];
$monthMDec = $row['MDec'];
?>
<tr>
<td><?php echo $studentId.' '.$studentFullName; ?></td>
<td><?php echo $subject.' '.$standard.'<br>'.$courseFee; ?></td>
<td id="0"><?php echo $monthJan; ?></td>
<td id="1"><?php echo $monthFeb; ?></td>
<td id="2"><?php echo $monthMar; ?></td>
<td id="3"><?php echo $monthApr; ?></td>
<td id="4"><?php echo $monthMay; ?></td>
<td id="5"><?php echo $monthJun; ?></td>
<td id="6"><?php echo $monthJul; ?></td>
<td id="7"><?php echo $monthAug; ?></td>
<td id="8"><?php echo $monthSep; ?></td>
<td id="9"><?php echo $monthOct; ?></td>
<td id="10"><?php echo $monthNov; ?></td>
<td id="11"><?php echo $monthMDec; ?></td>
<td><?php echo $paid.'/- '; ?></td>
<td><?php echo $studentStartDate; ?></td>
</tr>
<?php endwhile; ?>
</table>
function formatPay($value, $date, $date2) {
if($value == 0) {
if(strtotime($date) < strtotime($date2) {
$output = '-';
} else {
$output = 'Pay';
}
} else {
$output = $value;
}
return $output;
}
$studentStartDate = $row['studentstartdate']; // this is the J.date
$monthJan = formatPay($row['MJan'],$studentStartDate,'01-01-2018');
$monthFeb = formatPay($row['MFeb'],$studentStartDate,'01-02-2018');
$monthMar = formatPay($row['MMar'],$studentStartDate,'01-03-2018');
$monthApr = formatPay($row['MApr'],$studentStartDate,'01-04-2018');
$monthMay = formatPay($row['MMay'],$studentStartDate,'01-05-2018');
$monthJun = formatPay($row['MJun'],$studentStartDate,'01-06-2018');
$monthJul = formatPay($row['MJul'],$studentStartDate,'01-07-2018');
$monthAug = formatPay($row['MAug'],$studentStartDate,'01-08-2018');
$monthSep = formatPay($row['MSep'],$studentStartDate,'01-09-2018');
$monthOct = formatPay($row['MOct'],$studentStartDate,'01-10-2018');
$monthNov = formatPay($row['MNov'],$studentStartDate,'01-11-2018');
$monthMDec = formatPay($row['MDec'],$studentStartDate,'01-12-2018');
Unless I made a typo somewhere, this should work. Since your code is kind of messy, it's easiest to just make a function that handles this conversion.
I think what you are after is something like this. You could do this in the SQL but since you asked for a php solution, here it is.
I stripped out the query and reformatted some of the html to gain some vertical space.
I also used a button template that you can adjust which ever way you want. I used an array for the months and loop through it and then loop again in the html table cols. The array is not necessary but I prefer to do my calculations outside of my view/template. Also this makes it easier to understand/read.
<?php
$sqlFees = <<<SQL
...
SQL;
$resultFees = mysqli_query($con, $sqlFees);
$buttonTemplate = '<button data-studentid="%s">Pay</button>';
?>
<table border="1" cellpadding="8" style="border-collapse: collapse;">
<thead>
<th>Name</th><th>Subject</th>
<th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th><th>May</th>
<th>Jun</th><th>Jul</th><th>Aug</th><th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>
<th>Paid so far</th>
<th>Start date</th>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($resultFees)) :
$button = sprintf($buttonTemplate, $row['student_id']);
$joinDate = \DateTime::createFromFormat('Y-m-d H:i:s', $row['studentstartdate']);
$joinMonth = $joinDate->format('m');
$courseFee = $row['coursefee'];
$payments = [ $row['MJan'], $row['MFeb'], $row['MMar'], $row['MApr'], $row['MMay'],
$row['MJun'], $row['MJul'], $row['MAug'], $row['MSep'], $row['MOct'], $row['MNov'], $row['MDec']];
$buttons = [];
foreach ($payments as $month => $paid) {
if($joinMonth > ($month + 1)) {
$buttons[$month] = '-';
continue;
}
if(0 === (int)$paid) {
$buttons[$month] = $button;
continue;
}
$buttons[$month] = $paid;
}
?>
<tr>
<td><?= $row['firstname'] . ' ' . $row['lastname']; ?></td>
<td><?= $row['subject'] . ' ' . $row['standard'] . '<br>' . $row['paid']; ?></td>
<?php foreach($buttons as $mon => $but): ?>
<td id="<?= $mon; ?>"><?= $but; ?></td>
<?php endforeach; ?>
<td><?= $row['paid']; ?></td>
<td><?= $row['studentstartdate']; ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
The important bit is :
foreach ($payments as $month => $paid) {
if($joinMonth > ($month + 1)) {
$buttons[$month] = '-';
continue;
}
if(0 === (int)$paid) {
$buttons[$month] = $button;
continue;
}
$buttons[$month] = $paid;
}
In the first if, it checks if the student was actually joined, (and since i used an array index, i need to add one to the month).
In the second if, it checks to see if there was no payment made and adds the button.
And by default it shows the value paid.
One thing to note is that you could do this in an if-elseif-else structure, but i'd like to show some different way of addressing this, and this way is also slightly faster (micro optimizations)
your question is unclear but i'll give a try.
You could do something like this :
$date = date_create_from_format('d-m-Y', $j.date);
then in your table :
<?= $date->format('m') < $yourMonth ? '-' : $date->format('m') == $yourMonth ? $yourNumber : $date->format('m') +1 == $yourMonth ? 'Pay' : $yourNumber ?>
Hope this will be helpful
I am pulling out data from my "facebook" table using this code that I then display in a table using the foreach() function:
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
How would I go about pulling out data from multiple tables, for example from the "facebook" AND "twitter" table and then displaying it at the same time in my table?
Here is my full code for those that would need that:
<table class="table">
<thead>
<tr>
<td># (ID)</td>
<td>URL</td>
<td>Current Amount</td>
<td>Amount Wanted</td>
<td>Date</td>
<td>Status</td>
</tr>
</thead>
<tbody>
<?
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
if(!$orders){ echo '<tr><td colspan="6" align="center"><b>Noting found!</b></td><tr>';}else{
foreach($orders as $order){
?>
<?
if($order['status'] == 0){
$status = '<label style="color: #999999;">Waiting for supplier</label>';
}
elseif ($order['status'] == 1) {
$status = '<label style="color: #f0ad4e;">In progress</label>';
}
elseif ($order['status'] == 2) {
$status = '<label style="color: #e25856;">Canceled/Refunded</label>';
}
elseif ($order['status'] == 3) {
$status = '<label style="color: #428bca;">Pending admin review</label>';
}
else{
$status = '<label style="color: #94b86e;">Completed</label>';
}
?>
<tr>
<td><?=$order['id']?></td>
<td><?=$order['url']?></td>
<td><?=$order['c_amount']?></td>
<td><?=$order['amount']?></td>
<td><?=date('Y-m-d h:i',$order['date'])?></td>
<td><?=$status?></td>
</tr><?}}?>
</tbody>
</table>
Use the UNION keyword.
Please note that both queries should have the same fields count and the same fields types.
Example :
$orders = $db->QueryFetchArrayAll(
"SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='"
. $data['id']
. "' UNION
SELECT field1, field2, field3, field4, field5 FROM `twitter` WHERE some_condition "
);
Hope it helps
You would want to use a union
$orders = $db->QueryFetchArrayAll("SELECT id,url,
c_amount,amount,date,status FROM `facebook`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30
UNION
SELECT id,url,
c_amount,amount,date,status FROM `twitter`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30");
I have a table which has a field isClaimed that has only two fixed values = CLAIMED or NOT CLAIMED. I have to calculate the total of each field.
FYI, assume this is my table:
name | isClaimed
Aye | NOT CLAIMED
Ian | CLAIMED
Jan | NOT CLAIMED
Zen | NOT CLAIMED
Pom | CLAIMED
Total of unclaimed: 3
Total of claimed: 2
And please check my code below:
<?php
$sql = "SELECT pro.ScholarId, pro.Lastname, pro.Middlename, pro.Firstname, pro.Address, levels.LevelName, school.SchoolName, barangays.BarangayName, payroll.Allowance, sp.Points, pro.ScholarPointId, sca.isClaimed
FROM scholar_profile as pro
JOIN scholar_school as school ON pro.SchoolId = school.SchoolId
JOIN levels ON pro.LevelId = levels.LevelId
JOIN barangays ON pro.BarangayId = barangays.BarangayId
JOIN payroll ON payroll.PayrollId = levels.PayrollId
INNER JOIN scholar_points as sp ON pro.ScholarPointId = sp.ScholarPointId
JOIN scholar_claim_allowance as sca ON pro.ScholarId = sca.ScholarId
ORDER BY pro.LevelId, pro.ScholarId";
// OREDER BY id DESC is order result by descending
$result2 = mysql_query($sql);
if($result2 === FALSE) {
die(mysql_error()); // TODO: better error handling
}
// Start looping table row
while ($row2 = mysql_fetch_array($result2)) {
$firstname = $row2["Firstname"];
$lastname = $row2["Lastname"];
$middlename = $row2["Middlename"];
$barangay = $row2["BarangayName"];
$level = $row2["LevelName"];
$allowance = $row2["Allowance"];
$isClaimed = $row2["isClaimed"];
?>
<tr>
<td class="spec"><?php echo $lastname.", ".$firstname. " " .substr($middlename, 0,1) . "." ; ?> </td>
<td><?php echo $barangay; ?></td>
<td><?php echo $level; ?></td>
<td><?php echo $allowance; ?></td>
<td><?php echo $isClaimed ?></td>
</tr>
<?php
// Exit looping
}
?>
<tr>
<td colspan="4" class="spec">Total of unclaimed allowances</td>
<td></td>
</tr>
<tr>
<td colspan="4" class="spec">Total of claimed allowances</td>
<td></td>
</tr>
I have tried the tutorial from here: http://www.randomsnippets.com/2008/10/05/how-to-count-values-with-mysql-queries/
But i can't get it to work in php.
From the tutorial you linked....
$sql = "SELECT
SUM(IF(sca.isClaimed = "CLAIMED", 1,0)) AS claimedTotal,
SUM(IF(sca.isClaimed = "NOT CLAIMED", 1,0)) AS notClaimedTotal,
pro.ScholarId, pro.Lastname, pro.Middlename, pro.Firstname, pro.Address, levels.LevelName,
school.SchoolName, barangays.BarangayName, payroll.Allowance, sp.Points, pro.ScholarPointId, sca.isClaimed
FROM scholar_profile as pro
JOIN scholar_school as school ON pro.SchoolId = school.SchoolId
JOIN levels ON pro.LevelId = levels.LevelId
JOIN barangays ON pro.BarangayId = barangays.BarangayId
JOIN payroll ON payroll.PayrollId = levels.PayrollId
INNER JOIN scholar_points as sp ON pro.ScholarPointId = sp.ScholarPointId
JOIN scholar_claim_allowance as sca ON pro.ScholarId = sca.ScholarId
ORDER BY pro.LevelId, pro.ScholarId";
And then
echo $row2["claimedTotal"];
and
echo $row2["notClaimedTotal"];
Note that I used the table sca for for the isClaimed value, just a guess...not sure of your table structure, maybe you will need to change sca to reflect the correct table.
<?php
$claimedCount = 0;
$unclaimedCount= 0;
$sql = "SELECT pro.ScholarId, pro.Lastname, pro.Middlename, pro.Firstname, pro.Address, levels.LevelName, school.SchoolName, barangays.BarangayName, payroll.Allowance, sp.Points, pro.ScholarPointId, sca.isClaimed
FROM scholar_profile as pro
JOIN scholar_school as school ON pro.SchoolId = school.SchoolId
JOIN levels ON pro.LevelId = levels.LevelId
JOIN barangays ON pro.BarangayId = barangays.BarangayId
JOIN payroll ON payroll.PayrollId = levels.PayrollId
INNER JOIN scholar_points as sp ON pro.ScholarPointId = sp.ScholarPointId
JOIN scholar_claim_allowance as sca ON pro.ScholarId = sca.ScholarId
ORDER BY pro.LevelId, pro.ScholarId";
// OREDER BY id DESC is order result by descending
$result2 = mysql_query($sql);
if($result2 === FALSE) {
die(mysql_error()); // TODO: better error handling
}
// Start looping table row
while ($row2 = mysql_fetch_array($result2)) {
$firstname = $row2["Firstname"];
$lastname = $row2["Lastname"];
$middlename = $row2["Middlename"];
$barangay = $row2["BarangayName"];
$level = $row2["LevelName"];
$allowance = $row2["Allowance"];
$isClaimed = $row2["isClaimed"];
?>
<tr>
<td class="spec"><?php echo $lastname.", ".$firstname. " " .substr($middlename, 0,1) . "." ; ?> </td>
<td><?php echo $barangay; ?></td>
<td><?php echo $level; ?></td>
<td><?php echo $allowance; ?></td>
<td><?php echo $isClaimed ?></td>
</tr>
<?php
if($row2["isClaimed"] == "CLAIMED")
$claimedCount++;
elseif($row2["isClaimed"] == "NOT CLAIMED")
$unclaimedCount++;
// Exit looping
}
?>
<tr>
<td colspan="4" class="spec">Total of unclaimed allowances</td>
<td><?php echo $unclaimedCount;?></td>
</tr>
<tr>
<td colspan="4" class="spec">Total of claimed allowances</td>
<td><?php echo $claimedCount;?></td>
</tr>
Note: I have not checked you query. I have just mentioned my suggestion about getting the count that suits your current structure. Moreover, its highly recommended to start using mysqli_* instead of mysql.