I am in the beginning of building a simple absence script for teachers to administrate students.
I need to populate the same list of students in 5 tables. One table for each day of the current week (monday to friday).
I have the following code at the moment
List students SQL query:
SELECT s.student_id, s.student_firstname, s.student_lastname,
a.student_absence_startdate, a.student_absence_enddate, a.student_absence_type
FROM students s
LEFT JOIN studentabsence a ON a.student_id = s.student_id
WHERE a.student_absence_startdate
IS NULL OR
'2012-06-20'
BETWEEN
a.student_absence_startdate AND a.student_absence_enddate
This query selects all students and joins another table wich is a linking table that holds the absence information for students.
I the populate the code 5 times like this:
<?php
$data = array();
while ($row = mysql_fetch_array($list_students)) {
$data[] = $row;
}
?>
<table>
<?php
foreach($data as $row){
$class = "";
if ($row['student_absence_type'] == 2) {$class = " style='background:#f00;'";}
else if ($row['student_absence_type'] == 3) {$class = " style='background:#8A2BE2;'";}
echo "<tr><td$class>";
echo "<a class='ajaxlink' href='#' rel='pages/ajaxAbsence.php?student_id=".$row['student_id']."'>".$row['student_firstname']." ".$row['student_lastname']."</a>";
echo "</td></tr>\n";
}
?>
</table> <!-- Repeat -->
My question is how I should manage the date functions.
As you can see in my SQL query I have hardcoded the dates. I need it to automatically select the date of wich table the students are listed.
for example:
table > Monday (2012-07-23)
the user John Doe has absence information in this span, based on the above query. Let's change the background of <td>
table > Tuesday (2012-07-24)
the user John Doe has no absence information in this span. Just list him.
etc...
I am not expecting you to write my code. I am just curious on how to think. I am fairly new to programming.
The most flagrant error I find in your thoughts is that you don't need those five tables. You'll end up repeating and messing data.
You need different tables, from what I've read.
Students
ID, Name, etc..
Classes
class_id, name,
Teachers
Id_teacher, name, etc
TeachersInClass (so you can now which teachers gave a specific class)
id, id_teacher, id_class
Absences
id, id_student, id_class, date
This leaves you a more robust database, and you can play arroud with multiple associations like, which teachers had the most absences in a year... etc etc.
EDIT: Forgot to answer your "real" question.
You can use the PHP DateTime class to manipulate your dates. It's easy to use, and the php.net has a lot of good examples to give you a boost start
Related
I am currently working on a school time-table management system wherein the student dashboard, Time-table is displayed according to the current day, but when displaying the data, two duplicates come out of nowhere.
Initially, I joined the tables 'students' and 'timetable' through an 'INNER JOIN', but the problem with it was duplicates being placed simultaneously which was later fixed with 'RIGHT JOIN'.
Now, the duplicates display after the entire table has been printed.
HERE IS THE CODE BELOW:-
<?php
require_once("connection.php");
function information($subject, $time, $day, $teacher){
$element = "
<tr>
<td>$subject</td>
<td>$time</td>
<td>$day</td>
<td>$teacher</td>
</tr>
";
echo $element;
}
function getData(){
global $conn;
$sql = '
SELECT DISTINCT students.roll_no
, students.class_room
, timetable.subject_name
, timetable.time_code
, timetable.day_otw
, timetable.teacher_name
FROM students
RIGHT
JOIN timetable
ON students.class_room = timetable.room_no;
';
$result = mysqli_query($conn, $sql);
$mydate=getdate(date("U"));
if(mysqli_num_rows($result) > 0){
while($row=mysqli_fetch_assoc($result)){
if($mydate['weekday'] == $row['day_otw']){
information($row['subject_name'], $row['time_code'], $row['day_otw'], $row['teacher_name']);
}
}
} else {
echo "
<h1 class=\"check-data\">Sorry, You haven't been assigned a class yet!</h1>
<h3 class=\"ask\">Please contact your teacher/supervisor for more information.</h3>
";
}
}
getData();
?>
SO BASICALLY THE ENTIRE TABLE IS BEING DUPLICATED TWICE.
Outer joining makes no sense here. You neither want students without a timetable entry (LEFT OUTER JOIN), nor timetable entries without students (RIGHT OUTER JOIN). Then you are using DISTINCT because you are fightig duplicates, which is a bad idea, because thus you don't examine where the duplicates stem from. There should be no duplicates in the first place, so probably there is something wrong with the join criteria or data. You should fix this instead of looking for inappropriate workarounds.
Your join criteria is that the student is in the same room as the timetable entry. Why is the student associated a room? Do all the student's classes take place in the same room? In that case, yes, a class room would mean a class and then the tables would be related by the class (room). But if that were the case, you would get no duplicates.
I assume there to be something else to relate students with the timetable. Look for a student ID in the timetable. Something like:
SELECT s.roll_no, s.class_room, t.subject_name, t.time_code, t.day_otw, t.teacher_name
FROM students s
JOIN timetable t ON s.student_id = t.student_id
ORDER BY s.student_id, t.day_otw, t.time_code;
Or maybe there is something like an additional class ID, both student and timetable belong to? (The room in both tables would look strange then, however.) Maybe you don't know the database well enough. If this is the case, ask somebody who does.
From your screen, you only need to display timetable data, so there is no point to link to student table
Please consider using the following instead of your right join
SELECT
timetable.subject_name, timetable.time_code,
timetable.day_otw, timetable.teacher_name
FROM timetable
so i'm creating a schedule system and i'm trying to display the information for the appointment and also, userID's for those who have booked a possition.
I have created a table for Students, Classes and ClassAssosication where the ClassID and UserID are PK And FK from the other tables. I have created a join statement =
SELECT classes.ClassName, students.UserID
FROM classassociation
JOIN students
ON classassociation.UserID = Students.UserID
JOIN classes
ON classassociation.ClassID = classes.ClassID
WHERE classassociation.ClassID = 1;
Where it retrieves the UserID and ClassName for those who have booked a place for Class with the ID = 1 .
I am trying to create a PHP/HTML table where in a field for example, Monday 9AM, i can print out the join statement, for example, Methodology, 1 ,2 (user Id's).
Day | 9AM | 10AM
Monday | Methodology, 1,2 |
Tuesday | |
I need this done for multiple classes but trying to attempt one for now. I am unsure of how to do this, so any help will be appreciated. Thank you.
Your query as written will return a row for each ClassName/UserId pair - if there are two people in the methodology class there will be two rows in your query result.
You can choose to combine them in a loop in php, or you can alter your query to group things together. If you think of it as "I want to group all the UserIds for a given classname", it suggest how to use the GROUP BY clause in your SQL:
SELECT classes.ClassName, students.UserID
FROM classassociation
JOIN students
ON classassociation.UserID = Students.UserID
JOIN classes
ON classassociation.ClassID = classes.ClassID
WHERE classassociation.ClassID = 1
GROUP BY ClassName;
Now there will be one row for each ClassName, but you still need to tell MYSQL how to handle the multiple UserIds for each row. In your case, you want to have the UserIds joined together in a comma-separated list. Happily, there's a special section in the manual just for the functions you use with GROUP BY. In this case GROUP_CONCAT gives the desired result:
SELECT classes.ClassName, GROUP_CONCAT(students.UserID SEPARATOR ',') AS UersIds
FROM classassociation
JOIN students
ON classassociation.UserID = Students.UserID
JOIN classes
ON classassociation.ClassID = classes.ClassID
WHERE classassociation.ClassID = 1
GROUP BY ClassName;
Now you will get a result set with one row for each ClassName, with two columns:
ClassName | UserIds
---------------------
Methodology | 1,2
Then you can write a simple php loop to take each row in the query and generate a table row in your html.
If you look at the manual for GROUP_CONCAT, you can see that you can also set the order that the userIds are grouped in, which might be useful.
The php loop is pretty simple once you have your query results; you just need to create a table and then add a row for each result:
/*assume your mysql query has returned an array of objects named $result */
// in your html document, create your table with its header
print '<table><thead><tr><th>Class Name</th><th>UserIds</th></tr></thead>';
print '<tbody>';
// now loop through your query results and put stuff into the table
// of course you can monkey around with the table format and what goes in each cell
foreach($result as $row) {
print '<tr><td>'.$row->ClassName.'</td><td>'.$row->UserIds.'</td></tr>';
}
print '</tbody></table>';
That's a very simple example, but hopefully demystifies the process somewhat.
Your particular case looks like the query is actually to get the contents of one cell in your table; you can either do a much grander query that groups by time and day of week, or you can do little queries and store the results in nested arrays that model how you want your table to look. The html output is structurally the same, but you would have a php loop for each table cell.
To have table with each cell showing the result of a separate query, consider something like the following pseudocode:
$days = array('Monday', 'Tuesday',...'Friday');
$times = array('9', '10'...);
$weekResults = array();
foreach($days as $day) {
$weekResults[$day] = array();
foreach($times as $time) {
$weekResults[$day][$time] = doQuery($day, $time);
}
}
// now you have nested arrays with a result set for each table cell.
// Rendering the table, you just use the same loops:
renderTableHeader(); // all the <table><thead> stuff
foreach($weekResults as $day) {
print '<tr>'
foreach($day as $time) {
print '<td>';
// output the data from your query like above
// if the formatting is complex, you can even put another table inside the <td>.
print '</td>';
}
print '</tr>';
}
renderTableFooter(); // close tbody and table tags
Hope that helps!
I am sorry for a verlo long question, just trying to explain in details. My formatting is not very good, sorry for that as well. I had a PHP/ MySQL App that essentially was not truly relational as I had one large table for all student scores. Among other things, I was able to calculate the average score for each subject, such that the average appeared alongside a student's score. Now I have since split the table up, to have a number of tables which I am successfully querying and creating School Report Cards as before. The hardship is that I can no longer calculate the avaerages for any subject.
Since I had one table with 5 subjects and each of the subjects had 2 tests, I queried for data and calculated the average as follows:
The one table (Columns):
id date name exam_no term term year eng_mid eng_end mat_mid mat_end phy_mid phy_end bio_mid bio_end che_mid che_end
The one query:
$query = "SELECT * FROM pupils_records2
WHERE grade='$grade' && class='$class' && year = '$year' && term ='$term'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) > 0) {
$num_rows=mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
//English
$eng_pupils1{$row['fname']} = $row['eng_mid'];
$eng_pupils2{$row['fname']} = $row['eng_end'];
$mid=(array_values($eng_pupils1));
$end=(array_values($eng_pupils2));
$add = function($a, $b) { return $a + $b;};
$eng_total = array_map($add, $mid, $end);
foreach ($eng_total as $key => $value){
if ($value==''){
unset ($eng_total[$key]);
}
}
$eng_no=count($eng_total);
$eng_ave=array_sum($eng_total)/$eng_no;
$eng_ave=round($eng_ave,1);
//Mathematics
$mat_pupils1{$row['fname']} = $row['mat_mid'];
$mat_pupils2{$row['fname']} = $row['mat_end'];
$mid=(array_values($mat_pupils1));
$end=(array_values($mat_pupils2));
$add = function($a, $b) { return $a + $b;};
$mat_total = array_map($add, $mid, $end);
foreach ($mat_total as $key => $value){
if ($value==''){
unset ($mat_total[$key]);
}
}
print_r($mat_total);
$mat_no=count($mat_total);
echo '<br />';
print_r($mat_no);
$mat_ave=array_sum($mat_total)/$mat_no;
$mat_ave=round($mat_ave,1);
}
}
//Biology
etc
I split the table into separate tables and have names in a separate table, not needed for calculating avaerages, so I will not show it here. Each subject table tajkes the following form:
id date exam_no term year grade class test*
*Test would be eng_mid or eng_end or mat_mid etc.
Because I had only one query which returned 10 rows (5 subjects each with two tests: e.g. eng_mid (English Mit exam), eng_end (english end of term test), I was able to capture all rows in one call and pack each subject into an array, and then work out the class average, with the help of array_map. It may not be elegant, but it worked very well. Now, I have each test in it's own table.
I was trying to write a joint so as to get a signle resultset but the query fails. The columns as like:
I know that the database design is not anything to be proud off, but coming from a huge single table, this is a massive step (worthy a pat on the shoulder).
What I wish to do is to be able to query all my data and calculate class averages (about 30 students in each class). I tried to use separate queries but I ran into a wall, in that previously I would use the WHILE conditional as shown after the query for it to pull all rows and create an array from which I could get desired results. Now several queries just makes me confused as to how I can archieve the same results since a join is not working. Also I am having a separate $row variable, and that throws me further off balance!
Is it even possible to do averages as I did on my infamous one table (from the dark side) or is my table design so messed up, what I want just isn't humanly possible?
Please any help will be deeply appreciated.
Try using union. It would be something like
select grade, test from math
union all
select grade, test from english
union all
....
Also, in my opinion, better design would be to have table exams something like that (warning, pseudo-DML):
id int primary key,
student_id int foreign key students
subject_id int foreign key subjects
exam_type_id int foreign key exam_types
grade int(????)
exam_types table would be just midterm and final, but you'll be able to easily support more types in future, if required.
subjects table will store all kinds of subjects you have (at this time there will be only five of them: math, eng, phy, etc.
The averaging query would be as simple as (yes, you can actually do aggregation in the query itself)
select student_id, avg(grade)
from exams
group by student_id
EDIT: Added the first SQL query.
A section of my website has two dropdown menus. All the options in both are populated using SQL queries. Dropdown#1 is a list of class sections (like A1 for example). Once the professor selects a section, Dropdown#2 is populated with the student ID's (like 1234567 for example).
Student information is found in table 1. Among this information is the 'professorName' column. In order to associate the student with a class section, I need to match 'professorName' column with an identical column found in table 2, because class sections are only found in table 2.
Till here everything works great, because at the end of my query I put ORDER BY student ID. However, two of the class sections are associated to two different professors. In order to deal with this issue, I used the following code to loop through each professor name.
$from site = $_POST['section'];
$query = ("SELECT professorName FROM Table 2 WHERE classSection='$fromsite'");
$NumberofProfessorNames = $objMSSQL->getAffectedRows();
echo $NumberofProfessorNames;
for ($j=0; $j<$NumberofProfessorNames; $j++)
{
$section= $query[$j][professorName];
$output = $objMSSQL->getTable("SELECT DISTINCT StudentID from table1 WHERE professorName='$section' ORDER BY StudentID");
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
}
The problem is that for the only two sections where this is even necessary (because there are two professorNames), since it is looping like this, it is ending up ordered like this in the dropdown#2:
1234567
2345678
3456789
4567890
1234123
2345765
3456999
4567000
My limited experience in programming is keeping me from understanding how I can fix this seemingly simple issue.
Thank you for your help.
Rather than loop over the professors and query table1 for each, join table1 and table2 in the second query and only query the database once. For example:
$query = [... FROM Table2...];
$NumberofProfessorNames = $objMSSQL->getAffectedRows();
echo $NumberofProfessorNames;
$output = $objMSSQL->getTable("
SELECT DISTINCT StudentID
from table1
join table2
on ...
WHERE [the same clause you used in $query]
ORDER BY StudentID"
);
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
It's more elegant (and almost certainly more efficient) than generating a WHERE IN clause.
Yu can do it this way:
$section = "('";
for ($j=0; $j<$NumberofProfessorNames; $j++)
{
$section.= $query[$j][professorName] . "','";
}
$section = substr($section, 0, -3) . ')'; //$section contains ('prof1','prof2')
$output = $objMSSQL->getTable("SELECT DISTINCT StudentID from table1 WHERE professorName IN $section ORDER BY StudentID");
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
that is querying for all your professors in just one sql with IN() syntax.
UPDATE: I've just noted you use sql server instead of mysql, so I've changed the IN() syntax a bit and change the link to the sql server help docs.
It sounds like your tables aren't normalized. Good form would have a sections table, a students table, and a professors table. Information in each table should be specific to the table's topic.
students
student_id
student_last_name
student_first_name
student_address
etc
sections
section_id
section_name - multiple sections can tend to have the same name but differing content
section_description
section_year - sections can change from year to year
faculty
faculty_id
faculty_name - this is not a key field, more than one person can have the same name.
faculty_address
faculty_type - adjunct, fulltime, etc.
You would then have relational tables so you can associate professors with sections and students with sections.
faculty_2_sections
f2s_id
faculty_id
section_id
student_2_sections
s2s_id
student_id
section_id
This makes it super simple because if a student is logged in, then you already have their student id. If it's a professor, you already have their faculty_id
If you're pulling for students, your sql might look like this:
$sql = "select * from students s,sections sc,faculty f,faculty_2_sections f2s,student_2_sections s2s where student_id='$student_id' and s2s.student_id=s.student_id and s2s.section_id=sc.section_id and f2s.faculty_id=f.faculty_id and f2s.section_id=s2s.section_id";
If you're pulling for faculty you would do this:
$sql = "select * from students s,sections sc,faculty f,faculty_2_sections f2s,student_2_sections s2s where faculty_id='$faculty_id' and f2s.faculty_id=f.faculty_id and f2s.section_id=s2s.section_id and s2s.section_id=sc.section_id and s2s.student_id=s.student_id";
You can then pull a list of sections to populate the section_ids pull-down to only show students or faculty for a specific section.
I have a table that has patient information (name, dob, ssn, etc.) and a table that has lists of medications that they take. (aspirin, claritin, etc.) The tables are related by a unique id from the patient table. So, it's easy enough to pull all of Mary Smith's medications.
But, what I need to do is to show a paginated list of patients that shows their name, other stuff from the patient table and has a column with a line-separated list of their medications. Roughly, this:
If I do a simple left join, I get 3 repeated rows of Mary Smith with one medication per row.
The patient table can have thousands of records, so I don't want to do a query to get all the patients and then loop through and get their meds. And, because it's paginated based on patient, I can't figure out how to get the correct number of patients for the page, along with all their medications.
(The patients/medications thing is just a rough example of the data; so please don't suggest restructuring how the data is stored.)
GROUP_CONCAT to the rescue!
SELECT patients.first_name, patients.last_name, GROUP_CONCAT(prescriptions.medication SEPARATOR ", ") AS meds FROM patients LEFT JOIN prescriptions ON prescriptions.patient_id = patients.id GROUP BY patients.id;
You've got a few choices.
rowspan clauses with one drug per cell per user. You'd need to run two SQL queries to precalculate how big each user's span would have to be, or suck the query results into PHP and do the counting there.
Simple state machine - start a new row each time the user changes, then just keep adding more drug names seperated with <br /> while the user's name stays constant.
The second one's probably easiest:
$previous_name = null;
$first = true;
echo "<table";
while($row = mysql_fetch_assoc($results)) {
if ($row['name'] <> $previous_name) {
if (!$first) {
echo "</td></tr>"; // end previous row, if it's not the first row we've output
$first = false;
}
echo "<tr><td>$row[name]</td><td>"
$previous_name = $row['name'];
}
echo "$row['drug']<br />";
}
echo "</td></tr></table>";
I think what you are looking for is referred to a 'concation of subquery'.
Check http://forums.mysql.com/read.php?20,157425,157796#msg-157796 and http://mysql.bigresource.com/SELECT-CONCAT-Subquery-S5cIpzqO.html