Displaying results depending on its date (month & year) - php

I have load of data in the DB and each row has a date column
Currently im pulling all the results onto a page but i want to split it up into months.
I have buttons on my page that when clicked should display only the appropriate results, for example when the button January 2012 is click all the results for that month will be displayed
Heres an example of what im trying to achieve:
http://i.stack.imgur.com/PY7iN.jpg
=================================================================================
<?php
$con = mysql_connect("localhost", "username", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM tablename");
$num_rows = mysql_num_rows($result);
echo "<table border='0' cellspacing='0'>";
while($row = mysql_fetch_array($result))
{
$i++;
if($i%2==0) $class="cell1"; else $class="cell2";
echo "<tr class='$class'>";
echo "<td>".$row["firstname"]." ".$row["lastname"]." thinks that it will happen on
<span class=datecolor>".date('l jS F Y',strtotime($row['date']))."</span></td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
=========================================================================
Im looking for a little help on how i can display the results for each month by clicking on the buttons without it appearing all at the one time.
Also the when the page is first viewed id like it to automatically show the results for the current month, for example it if viewed now it would display the August results
Hope you can help

To address your first question (displaying one month at a time), your best bet is to make your database do all of the work for you. Right now your SQL SELECT statement looks like
SELECT * FROM tablename
You want to add a WHERE clause that will restrict this query to only show you rows for a certain month… something like
SELECT * FROM tablename WHERE date BETWEEN '05/01/2011' AND '05/31/2011'
You may need to tweak this for your particular database engine or setup. Here's one WHERE tutorial; you can find tons more on the web.

You can have all your buttons be links to the page with a query string that specifies the month (for example: www.mysite.com/mypage?month=september). Then get the month from the query string and only select the rows that are in that month.
See:
PHP parse_str()
$_SERVER['QUERY_STRING']
MySQL Select a Date Range

Something like
$month = isset($_GET['month']) ? intval($_GET['month']) : 0;
$year = isset($_GET['year']) ? intval($_GET['year']) : 0;
if( empty($month) ){
$month = date('n');
}
if( empty($year) ){
$year = date('Y');
}
$query = mysql_query('SELECT * FROM table_name WHERE MONTH(date_field)="'.$month.'" AND YEAR(date_field)='.$year.'"');
// or maybe use BETWEEN syntax
while( false!==($row=mysql_fetch_assoc($query)) ){
// do something...
}
Year is needed because one month number may belong to diffent year number (03-2010,03-2011 etc..), and, so when your data covers dates from different years, you cannot determine what data you need only having month

Related

PHP, looping through query results in SQL

I'm currently having trouble trying to create a loop for my desired outcome.
I'm currently creating a student record card which stores numerous data of different students (fake students).
I have created a query which returns the relevant data I need (see picture one, phpmyadmin)
SELECT mods.mid, mtitle, credits, enrl.ayr
FROM stud, smod, mods, enrl
WHERE stud.sid = '154279' AND stud.sid = smod.sid
AND smod.mid = mods.mid AND stud.sid = enrl.sid
ORDER BY `enrl`.`ayr` DESC
As you can see by the results, there are attributes:
mid
mtitle
credits
ayr
I have ordered by ayr in decending order. I am trying to make a loop that will run through the return on this query and print out each row until the end of whatever the current year is. Almost grouping all rows with the same year e.g. '2001/02' into a sub table which I can then name and print.
As you can see by my second picture of the student records page, I need to be able to print all records for the one year, then create a new header for the next existing year and print all containing rows for that.
{EDIT}
PHP Code:
$query = "SELECT mods.mid, mtitle, credits, enrl.ayr
FROM stud, smod, mods, enrl
WHERE stud.sid = '154279' AND stud.sid = smod.sid AND smod.mid = mods.mid AND stud.sid = enrl.sid
ORDER BY enrl.ayr DESC
";
$scap = '';
$curYear = $row['ayr'];
if($result = $link->query($query)) {
while ($row = $result->fetch_assoc() && $row['ayr'] == $curYear) {
$scap .= "<table id=\"test\" style=\"width:100%\">
<tr>
<td> " . $row['mid'] . " </td> <td> " . $row['mtitle'] . "</td> <td> " . $row['credits'] . " <td> " . $row['ayr'] . "</td>
</tr>
</table>";
}$result->free();
}
Thanks in advance.
Let's say you commit to one query max for the whole page. Like I said in comments
I would have a variable, call it $curYear. Start it out as some junk
string. In your loop, if the cur year thing is different than
$curYear, create a new segment in your output but regardless update
$curYear variable
That was not meant to interfere with your existing source code (that much). It is just a sentinel to alert you to a year change (year/term whatever).
So it starts as some junk value, like "797fsdf*"
Now inside your while, remember, you have ALL the years coming in from that result set for all years.
Do what I said in that pink block above comparing that variable $curYear to
$row['ayr']
When those two values are different, time to do whatever HTML treatment you want (creating a new html table, a new div, who cares). Let's call this the separation thing.
Regardless, after you output the row, make sure you have set $curYear to $row['ayr']. Why is that important? Because the next loop you want to know if you need to do the separation thing.
The tricky part is if you are doing html tables, you have to close out the previous table (prior year) if you are not on your first year

Creating a table of dates from a database

Before I begin I'm not asking for a solution - as I'm trying to learn I'm just looking for some pointers so I can work it out myself.
I'm currently learning php and mysql, and have been given the task of creating a resource booking table and form. A form places a name, resource, start and end date into a database, and then this needs to be extracted and displayed as a table on a web page, so users can see if there is a meeting already booked at their desired time.
Final product mockup:
Here is the database table I made in phpmyadmin (called "meetings"):
I've written a while loop to loop through hours (from 8:00 to 19:00). This works left to right not up and down, so when checking if a meeting is already booked I'll have to search for 8:00 monday, then 8:00 tuesday etc:
$i = 8;
while($i < 20)
{
echo "<tr>".
"<td>".$i.":00</td>".
"<td></td>".
"<td></td>".
"<td></td>".
"<td></td>".
"<td></td>".
"<td></td>".
"</tr>";
$i++;
}
and I've started a function "isMeeting" but I have no idea where to go from here
function isMeeting()
{
$query= "SELECT * FROM meetings"; //WHERE hour part of start datetime field is $hour?
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
}
}
What would be my next steps to populating the table?

Create multiple select depending on previous choices with values from DB

Can anybody help me how to obtain this with (php/js or jquery)? I'm still beginner.
I have table in mysql which contains beyond other (and I don't know it before checking the DB)
name of company (for ex. Abc, Def...)
year
month
and some data for each month different ones
I need to create a form which in first select field I load available name of company. When user select one of them (Abc) it should display only appropriate year - filled for that company (2000, 2008, 2012) and etc. for (selected year just filled month).
I've done working the first part (bellow) but how to handle with different selects for different companies if I don't know possible combinations without checking DB.
<?php
echo "Select company: <select name=\"company\">";
$con=connect();
$result = mysqli_query($con,"SELECT * FROM Company");
while($row = mysqli_fetch_array($result)) {
echo "<option value=\"".$row['Name']."\">".$row['Name']."</option>";
}
mysqli_close($con);
echo "</select><br>";
?>
in order to do that you need to use Ajax , suppose the ajax file is relatedYears.php
in relatedYears.php, write the following code
<?php
$con=connect();
$result="";
//this is the company name sent by url using ajax in the main page
$company_name= $_GET['company_name'];
$query= "SELECT years FROM COMPANY WHERE company = $company_name";
$x=mysql_query($query) or die('error query');
$years=array();
while($row=mysql_fetch_row($x))
$years[]= $row[0];
foreach($years as $year)
$results .= "<option value='".$year."'>".$year."</option>";
echo $results;
?>

Showing database entries on a PHP calendar

I'm creating a web-based booking system where a user can add bookings into a database, and the details stored in the database are (among others) "DateBooked, StartTime, EndTime, Room".
Here's the bit that pulls the relevant info for the day the user has clicked on from the database:
$query="SELECT * FROM bookings WHERE DateBooked = '{$year}-{$selectedmonth}-{$selectedday}'";
$result = mysql_query($query);
$todayarray = mysql_fetch_array($result);
And the PHP:
$roomcount = 4;
$room = 1;
while ($room <= $roomcount)
{
echo "\n<div class=\"roomtimes\">";
echo "\n<table border=1>";
echo "\n<tr><th class=\"titlecell\">Room $room</th></tr>";
$cellnum = 10;
while ( $cellnum < 23 )
{
echo "\n<tr>";
echo "\n<td class=\"linkcell";
if ($selectedtime==$cellnum)
{
echo " selectedcell";
}
echo "\">";
echo "$cellnum:00</td>";
echo "\n</tr>";
$cellnum++;
}
$room++;
echo "\n</table>";
echo "\n</div>";
}
So my question is, how can I add a bit of text saying "BOOKED" inside each table cell if a entry exists for that room and the number in that cell is in between the start time and end time of that booking?
I'm new to this site so let me know if I've done something wrong or you need more information, thanks!
You need to divide the cell content html and insert your "BOOKED" text there. And I suggest you use mysql_fetch_assoc so you get and associative array and it's easier to get the fields. If I'm understanding your code correctly you might be able to use something like this. This example is a replacement for the row that has the link output in it. I've used mysq_fetch_assoc here to get the StartTime and EndTime fields from the database. You might need to change the fields a bit depending in what data format they are.
echo "$cellnum:00";
if ($todayarray['StartTime'] <= $cellnum && $todayarray['EndTime'] >= $cellnum && $todayarray['Room'] == $room) echo 'BOOKED';
echo "</td>";

How do I loop through results and display day of the week once at every change in day using php and mysql?

with my current query and loop:
$sched = mysql_query("SELECT *
FROM `shows`
ORDER BY `shows`.`show_time` ASC")
or die(mysql_error());
echo "<ul>";
while($row = mysql_fetch_array($sched)){
echo "<li><a href=\"#$row[id]\">";
echo $row['title'];
echo "</li>";
}
echo "</ul>";
This works great for displaying my results like this:
Name of show 1
Name of show 2
Name of show 3
However, I want to add an item to the list at the beginning of every change in day so it would display as follows:
Monday
Name of show 1
Name of show 2
Tuesday
Name of show 3
Wednesday
Name of show 4
I can't quite wrap my brain around the loop needed to do this. It might be helpful to know that the field 'show_time' is a datetime type, so it has the information for both time and day of week.
Thanks.
Simple tweak:
echo "<ul>";
$curDay='';
while($row = mysql_fetch_array($sched)){
$d=date('l',strtotime($row['show_time']));
if($d!=$curDay){
echo '<li>'.$d.'</li>';
}
$curDay=$d;
echo '<li><a href="#',$row['id'],'">',$row['title'],"</li>";
}
echo "</ul>";
Initialize $curDay, and then each time through the loop, check to see if the particular day is different than the last time through the loop (or different from the initial value)
The best way to do this is to keep a flag in your loop, and compare to the previous value.
Eg.
$previousDay = '';
while($row = mysql_fetch_assoc()) {
if ($previousDay != date('l', $row['show_time'])) {
echo '<h2>' . $date('l', $row['show_time']) . '</h2>';
}
...
$previousDay = date('l', $row['show_time']);
}
Adjust your query to sort by show_time first.
"SELECT * FROM `shows` ORDER BY `show_time`, `shows` ASC"
Then keep track of the current day as Shad suggests, parsing show_time to determine the day.

Categories