Show all the data from the given date through php condition - php

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

Related

Group by ( remarks ) Value in php mysql

Below is products table :
id | mid | wgh | remark| remkok |
1 3 1.5 r3ok 1
2 2 1.5 0
3 2 0.6 nice 0
4 1 1.2 okh 0
5 4 1.5 bye 0
6 4 2.4 okby 0
7 3 3.0 oknice 1
I want to display remark below tr of group by mid..like below
mid wgh
3 1.5
3.0
remarks : r3ok, oknice
4 1.5
2.4
remarks : bye, okby
2 1.5
0.6
remarks : , nice
1 1.2
remarks : okh
What I have tried as below :
$pid= null;
while($row = mysql_fetch_array($result))
{
$rowpkts = $row['mid'];
echo "<tr class=\"undercl\">";
if($rowpkts != $pid){
echo'<td align="center" valign="top">'.$row["mid"].'</td>';
}else{
echo'<td align="center" valign="top"></td>';
}
echo'<td align="center" valign="top">'.$row["wgh"].'</td>';
echo "</tr>";
// what i tried to build for remarks as below
$remsql = "SELECT mid as onu , GROUP_CONCAT(`remark` ORDER BY `id` ASC SEPARATOR ', ') AS plrmks
FROM products WHERE 1=1 GROUP BY `mid`";
$fetchremk = mysql_query($remsql);
$rowresults = mysql_fetch_array($fetchremk);
if($rowresults['onu'] == $pid ){
echo"<tr style='border-style:underline;'>";
echo'<td align="center" align="top">'.$rowresults["plrmks"].'</td>';
echo"</tr>";
}
}
$pid = $rowpkts;
}
But remarks is not coming proper below tr... it means its not display below mid=3 or mid=1.
Any other way,that would help me.
Add appropriate colspan as required and do not do center align.
Try below code
while($row = mysql_fetch_array($result))
{
$rowpkts = $row['mid'];
echo "<tr class=\"undercl\">";
if($rowpkts != $pid){
echo'<td align="center" valign="top">'.$row["mid"].'</td>';
}else{
echo'<td align="center" valign="top"></td>';
}
echo'<td align="center" valign="top">'.$row["wgh"].'</td>';
echo '</tr>';
$remsql = "SELECT mid as onu , GROUP_CONCAT(`remark` ORDER BY `id` ASC SEPARATOR ', ') AS plrmks
FROM products WHERE `remkok`= 1 GROUP BY `mid`";
$fetchremk = mysql_query($remsql);
$rowresults = mysql_fetch_array($fetchremk);
if($rowresults['onu'] == $pid ){
echo"<tr><td colspan ='?'> Remarks : ";
echo $rowresults["plrmks"];
echo "</td></tr>";
}
$pid = $rowpkts;
}

joining 4 tables in mysql statement in php

i dont know how to explain it well but what i want is that i want to display the instrutors name and courses title in my subject table and the day&time of the subject and at first i can display the subjects with its instructor name and course title but when i display the day&time of it.it dont fit on my desired output..
here is my sample code:
//subjectClass.php
public function subjects(){
global $db;
$sql = "
SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT
JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT
JOIN courses_tbl c
ON c.course_id = s.course_id
LEFT
JOIN subject_day_tbl d
ON d.subject_id = s.subject_id;
";
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$list[] = $row;
}
}else{
$list = NULL;
}
return $list;
}
//subjects.php
//include 'subjectsClass.php';
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>Subject Code</th>
<th>Subject Title</th>
<th>Unit</th>
<th>Section</th>
<th>Course</th>
<th>Instructor</th>
<th>Day/Time</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?>
<tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " " . $value['mid_name'] . ". " . $value['last_name'] ; ?></td>
<td>
<?php echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />"; ?>
</td>
<td>Edit | Delete</td>
</tr>
<?php
}
?>
</tbody>
and here is the output:
Subject Code Subject Title Unit Section Course Instructor Day/Time
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Monday [07:30:00 - 09:00:00]
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Wednesday [08:30:00 - 10:00:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Tuesday [07:00:00 - 08:30:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Thursday [07:00:00 - 08:30:00]
my desired output is this one:
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| Subject Code | Subject Title | Unit | Section | Course | Instructor | Day/Time |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 131 | Security Issues and Principles | 3 | IT-R | BSIT | Darwin Paradela. Galudo | Monday [07:30:00 - 09:00:00] |
| | | | | | | Wednesday [08:30:00 - 10:00:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 050 | Database Management System 2 | 3 | IT-R | BSIT | Ronnie Pitt. Cambangay | Tuesday [07:00:00 - 08:30:00] |
| | | | | | | Thursday [07:00:00 - 08:30:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
my tables:
subjects_tbl
courses_tbl
instructors_tbl
subject_day_tbl
I hope I can help you.
Your issue seems to be the left join of subject_day_tbl. It is a one-to-many relationship (ie, there can be many records in subject_day_tbl for each record in subjects_tbl), and when you left join a one-to-many you'll get a duplicate of the "one" side for each row in the "many" side. The only way that you could do this in a single query is by using a subquery or group statement to concatenate the rows in the database engine... but that is really bad because you're mixing display with your data model.
While it is true in general that for performance one should avoid issuing too many queries to the database, premature optimization is the root of all evil. First, try to have clean, understandable code, then look for bottlenecks if you're having issues.
In this case, a second query is certainly best. This is how I would do it:
//subjectClass.php
protected function subject_days($subject_id)
{
// I don't know what type of object $db is it looks like ezSQL,
// but you get the idea
global $db;
$sql = "SELECT sub_day, start_time, end_time
FROM subject_day_tbl
WHERE subject_id = %s";
$query = $db->query($db->prepare($sql, $subject_id));
return ($query->num_rows > 0) ? $stmt->fetch_assoc() : array();
}
public function subjects()
{
global $db;
$sql = "SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT JOIN courses_tbl c
ON c.course_id = s.course_id
";
$list = array();
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$row['course_days'] = $this->subject_days($row['subject_id']);
$list[] = $row;
}
}
return empty($list) ? NULL : $list;
}
// subjects.php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?><tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " "
. $value['mid_name'] . ". "
. $value['last_name'] ; ?></td>
<td><?php foreach($value['course_days'] as $day) {
echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />";
}?></td>
<td>Edit | Delete</td>
</tr><?php
}
Also, not to be a pedant, but you should really be escaping your output before
echoing it, eg with htmlspecialchars.

SELECT SUM data rank and Resource id #9 error PHP

I have a website in which logged in members are stored under a table called ‘users’
‘users’ table
users_sales_guild_id | users_first_name | users_surname
555 | Jane | Smith
333 | John | Smith
111 | Mike | Myers
The users have sales data in a 'sales_points' field which is in a separate table called ‘sales_list’.
‘sales_list’ table
sales_id | users_sales_guild_id | sales_points | sales_entry_date
1 | 555 | 50 | 2013-02-31 00:00:00
2 | 333 | 30 | 2013-02-31 00:00:00
3 | 111 | 10 | 2013-02-31 00:00:00
4 | 555 | 50 | 2013-03-31 00:00:00
5 | 333 | 30 | 2013-03-31 00:00:00
6 | 111 | 10 | 2013-03-31 00:00:00
Essentially what I am trying to do is a query which:
A. Calculates the total amount of 'sales_points' for each user from 'sales_list'
B. Lists 100 users with the user having the most points at the top, then ranking the next highest below and so on...
C. Im not after a ranking number, just the order itself.
With the code below I am getting 100 users printing ok, however I am getting a ‘Resource id #9’ message in the ’Total Points’ column when it prints. Can anyone help?
What I am trying to print
Jane Smith | 100
John Smith | 60
Mike Myers | 20
Code:
<?php
require_once ('config.inc.php');
$page_title = '';
include ('header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= 'login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}?>
<h1>Rankings</h1>
<?php require_once ('database.php'); // Connect to the database.
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$query = "SELECT us.users_id, us.dealership_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_type,
de.dealership_id, de.users_dealer_name, de.class , de.region, de.state, de.users_dealer_code_id, de.users_dealer_code_new_id, de.users_model, de.pma
FROM users AS us, dealerships AS de
WHERE us.dealership_id = de.dealership_id
ORDER BY ’$total’ DESC
LIMIT 100";
$result = #mysql_query ($query);
// Table header.
echo '<table width="680"cellpadding="5" cellspacing="1" style="font-size:12px;">
<tr class="orangehead">
<td align="center"><b>Member</b></td>
<td align="center"><b>Title</b></td>
<td align="center"><b>Dealer</b></td>
<td align="center"><b>Category</a></b></td>
<td align="center"><b>Dealer Code</a></b></td>
<td align="center"><b>Total Points</a></b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color. New: ' . $row['users_sales_guild_new_id'] . '
// $entries = floor($row['sp_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left"><strong>' . $row['users_first_name'] . ' ' . $row['users_surname'] . '</strong></td> ';
echo '<td align="center">' . $row['users_type'] . ' </td>';
echo '<td align="center"> ' . $row['users_dealer_name'] . ' </td>';
echo '<td align="center"> ' . $row['class'] . ' </td>';
echo '<td align="center"> ' . $row['users_sales_guild_id'] . ' </td>';
echo '<td align="center"> ' . $total . '</td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
include ('footer.html'); // Include the HTML footer.
?>
You don't fetch you first result. Fetch it as an array (mysql_fetch_array()) for example.
// Execute query
$total_query = mysql_query("SELECT SUM(sales_points)
FROM sales_list, users
WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'");
// Fetch result
$total = mysql_fetch_array($total_query);
You echo this:
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
The variable $total contains the result of the query, which is a Resource. You should use mysql_fetch_assoc or a similar function to extract the result itself. It's best to give the SUM(sales_points) an alias, i.e. AS total_sales_points so you can fetch is easily.
By the way, the mysql_*-extension is soon-to-be deprecated. Good alternatives include MySQLi and PDO.
$query = mysql_query("SELECT SUM(sales_points) as points FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$row = mysql_fetch_object($query);
$total = $row->points;
You are echoing the mysql resource, you first need to fetch the results, then you can echo them.

display php / mysql column output as rows

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>

Count the total of a specific value in mysql/php

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.

Categories