joining 4 tables in mysql statement in php - 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.

Related

Show all the data from the given date through php condition

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

How to display multiple records with same id in html table in single row(in <td>)?

I have sql data result set having records as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
------------------------------------
1 | RAVI | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
I am displaying this data in view by using html table.
Whereas my requirement is, I want to display as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
| | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
meaning I want to display records with id 1 into one <td>
I am using php foreach loop to display result.
How can I achieve this?
My current code is as follows and is results into same as my first table whereas I want my view as in the second table.
<table class="table table-striped">
<tr >
<th>ID</th>
<th>Name</th>
<th>Hobbies</th>
</tr>
foreach($result as $row)
{
echo "<tr>
<td>".$row->id."</td>
<td>". $row->name."</td>
<td>". $row->hobbies."</td>
</tr>";
}
</table>
A quick way to approach this would be to modify your MySQL query to use GROUP_CONCAT(hobbies) to group all of a user's hobbies together. The query would look something like:
SELECT
id, name, GROUP_CONCAT(hobbies) AS hobbies
FROM
your_table
GROUP BY
id
This will group all of a user's hobbies in a comma-delimited list. To display it, you can use PHP's explode() and iterate over that:
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>';
$hobbies = explode(',', $row->hobbies);
foreach ($hobbies as $hobby) {
// output each hobby and decorate/separate them however you'd like
echo $hobby . '<br />';
}
echo '</td>';
echo '</tr>';
}
If you don't want the inner loop (or the ending <br /> that will pad the hobbies), you can use str_replace() instead:
echo str_replace(',', '<br />', $result['hobbies']);
This post may help you: Concatenate many rows into a single text string?
Just replace the , with </br>.
in each iteration, you must save the last ID, in the next iteration you must check it whether its value has been changed or not. Something like this:
$res = $this->db->query('.....');
$last_ID = '';
foreach ($res->result() as $row) {
if ($row->id != $last_ID) {
if (strlen($last_ID)>0) echo '</td></tr>';
echo '<tr>';
echo '<td>$row->id</td>';
echo '<td>$row->name</td>';
echo '<td>$row->hobbies';
} else {
echo '<br />'.$row->hobbies;
}
$last_ID = $row->id;
}
if ($res->num_rows() > 0) echo '</td></tr>';
Supposing you have your row in $row var and the ID is $row["ID"]
?>
<td id="<php echo $row["id"]; ?>">
<?php echo $row["id"]; ?>
</td>
<?php

Printing a table somewhat complex MYSQL query in PHP

I have a database with 2 tables User, Contact_List.
The User table for example looks like this:
U_id | U_email | U_password | U_mobileNo | U_name |
---------------------------------------------------
1 | a#b.c | aaa | 1234567 | Adam |
2 | b#b.c | bbb | 1234567 | Ben |
3 | c#b.c | ccc | 1234567 | Carl |
The Contact_list table looks like this. This table is table just consisting of foreign keys that relate two users together
U_id | U_contact_id
-------------------
1 | 2
2 | 3
Now the problem is my SQL/PHP query to display a table that consists of a specific users list of contacts.
This SQL query works fine and gives the results I want:
"SELECT cu.u_name, cu.u_email
FROM contact_list = c, user = u, user = cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id"
But this PHP code:
$con = mysqli_connect("dbname","dbuser","pbpass","db");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT cu.u_name, cu.u_email
FROM contact_list = c, user = u, user = cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id" ) or die(mysql_error());
echo "<table border='1'>
<th>Contact List</th>
<tr>
<th>Name</th>
<th>E-mail</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['u_name'] . "</td>";
echo "<td>" . $row['u_email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($con);
?>
That code just prints a blank table on the page.
What am I doing wrong here?
I am a complete noob using PHP any help or suggestions would be appreciated.
You want to retrieve all the contacts of user with id 2 so basically your query would look like this:
SELECT u.u_name, u.u_email
FROM contact_list cl
JOIN user u
ON cl.u_contact_id = u.u_id
WHERE cl.u_id = 2
Live DEMO.
What the above query does is, it will join the users information based on the u_contact_id and will list all the names and emails registered to it.
And your PHP would look like this:
<?php
// your database info here
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
if (!$stmt = $con->prepare("SELECT u.u_name, u.u_email
FROM contact_list cl
JOIN user u
ON cl.u_contact_id = u.u_id
WHERE cl.u_id = ?"))
die('Prepare Error: ' . $con->error);
$id = 2;
if (!$stmt->bind_param('i', $id))
die('Bind Parameters Error ' . $stmt->error);
if (!$stmt->execute())
die('Select Query Error ' . $stmt->error);
?>
<table border="1">
<th>Contact List</th>
<tr>
<th>Name</th>
<th>E-mail</th>
</tr>
<?php
$stmt->bind_result($name,$email);
while ($stmt->fetch())
{
?>
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $email; ?></td>
</tr>
<?php
}
echo "</table>";
$stmt->close();
$con->close();
Try to do a var_dump on $row, you may find out more on what went wrong, if no var_dump appears, no result return was returned, use mysqli_error to find out what went wrong
mysqli_error($con);
while($row = mysqli_fetch_array($result))
{
var_dump($row);
}
It could be a case issue
$row['u_name']
may be is
$row['U_name']
SELECT cu.u_name, cu.u_email
FROM contact_list c, user u, user cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id
Maybe it's just that I suffer insomnia, but that should work
In your query:
Your syntax for specifying table alias is wrong. There is no need for the = sign.
You are aliasing user as both u and cu, but seems like you can get by with just one.
Try the following:
SELECT cu.u_name, cu.u_email
FROM contact_list c, user u // Or alternatively: FROM contact_list AS c, user AS u
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id
By the way, when printing the <table>, you need to place <th> inside <tr> for valid HTML.
Also, in your $result = mysql_query (....) you ended it with or die (mysql_error()). It should be or die (mysqli_error()).

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.

Query result records to column for comparison

Is there anyway to achieve displaying query results into columns and have the records go to the next row?
Here's my SQL table:
------------SQL TABLE -----------
id | product_name | product_type
0 | Lorem | Table
1 | Ipsum | Chair
2 | Dolor | Lamp
3 | Sit | Chair
This is what I would like.
Lorem | Ipsum | Dolor | Sit |
------------------------------------------------------------
id | 0 | 1 | 2 | 3 |
type | Table | Chair | Lamp | Chair |
Desired output:
<table>
<tr>
<td> </td>
<td>Lorem</td>
<td>Ipsum</td>
<td>Dolor</td>
<td>Sit</td>
</tr>
<tr>
<td>id</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>type</td>
<td>Table</td>
<td>Chair</td>
<td>Lamp</td>
<td>Chair</td>
</tr>
</table>
This is my code, but I know this is terribly wrong. I'm just stuck on how to make a new row for a field if that makes sense using while and for loops.
echo '<table><tr>';
$i=1;
while($rows = mysql_fetch_array($result)){
echo '<td><table><tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['product_id'].
'</td><td>'.$rows['product_type'].'</tr></table></td>';
if($i %2 == 0) {
echo '</tr>
<tr>'; }
}
echo'
</tr>
</table>';
You need to rotate your data.
You could use something like this (untested):
// build query
$query = "SELECT id, product_name, product_type FROM whatevertableyouhave";
// query the database
$result = mysql_query($query);
// cols we are interested in (from the SQL query)
$cols = array(
'id',
'product_name',
'product_type';
);
// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
$rotated[$col] = array();
}
// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
foreach($cols as $col) {
$rotated[$col][] = $row[$col];
}
}
// echo html
echo "<table>";
echo "<tr>";
foreach($cols as $col) {
echo "<th>{$col}</th>";
}
echo "</tr>";
foreach($rotated as $col => $values) {
echo "<tr>";
foreach($values as $value) {
echo "<td>" . htmlentities($value) . "</td>";
}
echo "</tr>";
}
echo "</table>";
try this
echo '<table>';
while($rows = mysql_fetch_array($result)){
echo '<tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['id'].
'</td></tr><tr><td>'.$rows['product_type'].
'</td></tr>';
}
echo' </table>';

Categories