I'm making a calendar using PHP and have run into some issues:
I want the calendar to be more automated at the moment as I'm manually creating the table and putting the times and days in myself, which is fine, but my issue is that I'd need a SQL function for every single hour (from 10:00-17:00) for every single day which seems extremely inefficient.
My HTML table code is structured as such:
<tr>
<td>
<span>
<p style="float:left">10:00</p>
<p style="float:right"> (<?php echo $var->monday_10; ?>)</p>
</span>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
And I have this PHP function:
public function get_CalendarCount($conn)
{
// TODO: Comment this function
// TODO: If a booking goes over a time (eg. 13:00) then add to count
$sql =
"
SELECT DAYNAME(arrivalTime) AS day, COUNT(*) AS count
FROM bookings
WHERE HOUR(arrivalTime) = 10
AND DAYNAME(arrivalTime) = 'Monday'
";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$this->monday_10 = $row["count"];
}
}
else
{
echo "0 results";
}
}
As you can see, the time in this example (13.00) and day (Monday) is manually put in. How can I change this so it gets the time / day from the table and keep is as the same function for every td?
Furthermore, I would like to alter my SQL query (as shown in the PHP get_CalendarCount function) so that it checks if a booking in the database goes over a time (eg. arrivalTime 10:00 - pickupTime 12:00 - both 10:00 and 11:00 need to count as the booking is for the hours 10:00 & 11:00 (1 hour each):
Would really appreciate help as I'm a bit stuck here, can't really find anything for this solution.
This is not answering the logic, you should change but the question of using variables in your query, so you don't have to manually put them in. For your question about making the hour and dayname variable you need to change this:
public function get_CalendarCount($conn)
{
$sql ="SELECT DAYNAME(arrivalTime) AS day, COUNT(*) AS count
FROM bookings WHERE HOUR(arrivalTime) = 10 AND DAYNAME(arrivalTime) = 'Monday'";
into:
public function get_CalendarCount($conn,$hour,$dayname)
{
$sql ="SELECT DAYNAME(arrivalTime) AS day, COUNT(*) AS count
FROM bookings WHERE HOUR(arrivalTime) = ".$hour." AND DAYNAME(arrivalTime) = '" . $dayname ."'";
Related
I have a database where teams will have multiple entries each with different locations. Each entry will have a team name. So for example, team1 might appear several times but each time the location will be different.
The structure of the DB is (each of these represents a column header):
team_name, first_name, last_name, location, arrival_time
My current working code creates HTML tables grouped by team name but currently only creates one row to show the first location and the time of arrival for the first location. I need this to dynamically create more rows to show all locations and arrival times for each team.
The desired result would look like this -
https://codepen.io/TheBigFolorn/pen/LqJeXr
But current result looks like this -
https://codepen.io/TheBigFolorn/pen/qgMppx
And here is an example of how the DB table might look -
https://codepen.io/TheBigFolorn/pen/daqJze
I've tried breaking up the echo and adding a second while loop before the row that I want to apply the above logic to but it seems to break everything. Any input on how I get this to work without having to use separate queries for each team would be very much appreciated. I'm new to php so please go easy on me :)
<?php
$leaders = "SELECT *, COUNT(location) FROM my_example_table GROUP BY team_name";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='red-border'>
<h2>". $row["team_name"]. "<br><small>Total locations visited: ". $row["COUNT(location)"]. "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>
<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>
</table>
</div>
";
}
} else {
echo "0 results";
}
?>
Your problem is due to the GROUP BY, as you've probably realised. This is necessary in order to get a count per team, but causes the number of rows output to be only 1 per team - that's what grouping does. Fundamentally, running an aggregate query such as a COUNT or SUM is incompatible with also outputting all of the row data at the same time. You either do one or the other.
Now, you could run two queries - one to get the counts, and one to get all the rows. But actually you don't really need to. If you just select all the rows, then the count-per-team is implicit in your data. Since you're going to need to loop through them all anyway to output them in the HTML, you might as well use that process to keep track of how many rows you've got per team as you go along, and create the "Total number of locations" headings in your HTML based on that.
Two things are key to this:
1) Making the query output the data in a useful order:
SELECT * FROM my_example_table Order By team_name, arrival_time;
2) Not immediately echoing HTML to the page as soon as you get to a table row. Instead, put HTML snippets into variables which you can populate at different times in the process (since you won't know the total locations per team until you've looped all the rows for that team), and then string them all together at a later point to get the final output:
$leaders = "SELECT * FROM my_example_table Order By team_name, arrival_time;";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
$currentTeam = "";
$locationCount = 0;
$html = "";
$teamHtmlStart = "";
$teamHtmlEnd = "";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//run this bit if we've detected a new team
if ($currentTeam != $row["team_name"]) {
//finalise the previous team's html and append it to the main output
if ($currentTeam != "") $html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
//reset all the team-specific variables
$currentTeam = $row["team_name"];
$teamHtmlStart = "<div class='red-border'><h2>".$currentTeam."<br><small>Total locations visited: ";
$locationCount = 0;
$teamHtmlEnd = "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>";
}
$teamHtmlEnd .= "<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>";
$locationCount++;
}
//for the final team (since the loop won't go back to the start):
$html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
echo $html;
}
else {
echo "0 results";
}
Here's a runnable demo (using some static data in place of the SQL query): http://sandbox.onlinephpfunctions.com/code/2f52c1d7ec242f674eaca5619cc7b9325295c0d4
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
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?
I am trying to create a script where if the date is later than today then it will display an item from the table in MySQL.
$query = $dbc->query("SELECT event_id, name, location, image, DATE_FORMAT(Date, '%d-%b-%Y') AS Date, Date as FormatDate
FROM events
ORDER BY FormatDate ASC
");
$results = $query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
$name = $row['name'];
$image = $row['image'];
$location = $row['location'];
$Date = $row['Date'];
$Date = strtotime($Date);
$Date = date('d-M-Y', $Date);
$Data = explode("-", $Date);
if (strtotime($Date) >= time()){
$page->body("
<div class=\"event\">test
<img src=\"$image\" alt=\"$name\" class=\"event_image\"/>
<p class=\"event_title\">$name</p>
<p class=\"event_location\">$location</p>
<p class=\"event_time\">$Data[0] $Data[1] $Data[2]</p>
</div>
");
}else{
$page->body ("
<!-- alrge grey text 100% span -->
<div class=\"event\">
<p>There are currently no events happening.</p>
</div>
");
}
}
}
When I add an event to the table with a later date than today it adds successfully and the script runs and I can see the event printed out on the page because the date if greater than time().
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
I am stumped as to why the else statement doesn't bring back the failed notification if there is nothing in the table that is later than today.
Any help much appreciated.
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
The while statement will only execute if there are rows to process. Since you've cleared the table, it will never enter the while loop, and the else branch will never be encountered.
Because there are no rows to fetch and your code is not going inside while loop when your table is empty.
HTH!
I am making a page where people can make posts. All of those posts are then shown in a table of 24 cells. I can have the last 24 posts shown with no problem, but now I don't know how to show the prior group(s) of posts. How can I fix my code to do that? I actually have this:
(I'm removing lines to make it easy to read)
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC";
// ---check everything is fine---- //
function retrieve_info($result)
{
if($row = mysql_fetch_assoc($result))
{echo $topic_if; echo $topic_subject; //and what I want in every cell
}
}
<table width="100%" height="751" >
<tr><td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td></tr>
<!-- repeat a few more times :-) -->
</table>
I though that by changing the variable $row with a number before the if statement would alter the output, but I still see the same data printed on screen. What should I do to be able to show next group of posts?
Thanks!!!
At some point when you have hundreds or thousands of records, you are going to want to paginate the results and not just select all records from the table.
To do this you will run one query per 24 records, your sql would be more like this:
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC
LIMIT 0, 24
";
and for the next 24,
LIMIT 24, 24
then
LIMIT 48, 24
and so on.
You would then make next/previous buttons to click which would refresh the page and dispay the next 24, or you would get the next results with an AJAX request and append the next 24 through the DOM.
This suggests having to take a slightly different approach then calling the same function from each table cell.
More like get the relevant 24 results based on the page number you are on, then loop through the results array and print out the table code with values inside it. Based on if the iterator of the loop is divisible by 4 (looks like your grid is 4x6), you print out new tags for the new row, and that sort of thing.
Search around a bit for pagination in php and mysql to get a sense of how this all fits together.
function retrieve_info($result)
{
while($row = mysql_fetch_assoc($result))
{
$topic_id = htmlspecialchars($row['topic_id']);
$topic_subject = htmlspecialchars($row['topic_subject']);
echo '<td>';
echo $topic_if;
echo $topic_subject; //and what I want in every cell
echo '</td>';
}
}