Populating an HTML table with MySQL data, linked by calendar date - php

I am using the code below to generate a simple HTML table that displays the next 90 calendar days. Each day is a row in this simple table.
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td></tr>\n";
}
echo "</table>";
Also, I have a MySQL table with the following fields:
event varchar(1000)
datescheduled date
How can I make a second column in the aforementioned HTML table, containing "event" from the MySQL table, matched by date?

This can be tackled in numerous ways. Consider this example:
PHP
<?php
$con = mysqli_connect("localhost","dbuser","dbpass","database");
$query = mysqli_query($con, "SELECT * FROM event");
// First build the array of events, put the dates in keys, then the values as events
$events = array();
while($result = mysqli_fetch_assoc($query)) {
$events[$result['datescheduled']] = $result['event'];
}
?>
// Structure should be something like this:
Array
(
[2014-05-02] => Day of lorem
[2014-06-02] => Day of ipsum
[2014-07-02] => Day of days
)
HTML
<!-- the compare selected values on the current loop, check its keys -->
<?php $now = time(); ?>
<table border="1" cellpadding="10">
<?php for($i=0;$i<90;$i++): ?>
<?php $thisDate = date("Y-m-d", $now + ($i*86400)); ?>
<tr>
<td><?php echo $thisDate; ?></td>
<td><?php echo array_key_exists($thisDate, $events) ? $events[$thisDate] : ''; ?></td>
</tr>
<?php endfor; ?>
</table>

$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td>";
$result_set = mysql_query("SELECT event FROM eventTable WHERE datescheduled = STR_TO_DATE('{$thisDate}','%d/%m/%Y')'",$connection);
$result = mysql_fetch_assoc($result_set);
echo "<td>{$result['event']}</td></tr>\n";
}
echo "</table>";
Its worth noting that you will need to use a string to date function in mysql depending on how the date is stored.
Edit: in case you need further hand holding, here is the STR_TO_DATE function done for you.
STR_TO_DATE('{$thisDate}','%d/%m/%Y')
I have edited my code above to reflect this as to not strain your brain.
Even tossed in some screenshots of the table and the output, just because you were kind of an ass in your comment. With 5 years of experience i would have thought you would know how to echo out a simple table like this, or at the very least, have a little common courtesy when someone tries to help you.

Related

Need a loop to add 30 minutes as a time in HTML

i have made a webpage using html and php that allows users to book appointments, but my slots are every 30 minutes but the way i am currently doing it will not add 30 minutes on to the database
<?php ob_start( ); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Nav.css">
<title>Book Barber</title></head>
<body>
<?php
echo " <div class='navigation'><a href='BarberHomeScreen.php'>Home</a><div class='dropdown'><button class='dropdownButton'>Account<i class='fa fa-caret-down'></i></button><div class='dropdownContent'><a href='MyAccount.php'>My Account</a><a href='SignOut.php'>Sign Out</a></div></div></div>";
?>
<h1>Booking a barber appointment for <?php session_start();echo $_SESSION['customerName'];?></h1>
<form method="POST" action="#">
<input type="date" name="selectDate" />
<input type="submit" name="submitDate"/>
<?php
if(isset($_POST['submitDate'])){
//if the submit button has been pressed, connect to the db
//and search for all the available tables on that selected day
$conn = mysql_connect(localhost, "root", "");
if(!$conn){
die("Could not connect: " . mysql_error());
}
$selectedDb = mysql_select_db('booking', $conn);
if(!$selectedDb){
die("Can't use the selected db: " . mysql_error());
}
//selects all the bookings for the date chosen in the form
$query= "SELECT * FROM booking WHERE BookingDate = '" . $_POST['selectDate'] . "' ORDER BY customerID, BookingTime";
$result = mysql_query($query);
//stop php while table headers outputted
?>
<table border="1">
<tr></tr>
<tr>
<th>Barber</th>
<th>9:00</th>
<th>9:30</th>
<th>10:00</th>
<th>10:30</th>
<th>11:00</th>
<th>11:30</th>
<th>12:00</th>
<th>12:30</th>
<th>13:00</th>
<th>13:30</th>
<th>14:00</th>
<th>14:30</th>
<th>15:00</th>
<th>15:30</th>
<th>16:00</th>
</tr>
<?php //start php again to output the bookings available or not
/*The next bulk of php is outputting the table showing which slots are booked and which are available.
two while loops are needed, the outer one loops through the tables, the inner while loops through
each of the times for the table.
Then while the loops are repeating they check if this booking
is for the current timeslot and table being looked at. If so it puts an X in the td and carries out mysql_fetch_assoc
again to get the next booking from the $result. This continues for each of the slots in the table.
*/
$row = mysql_fetch_assoc($result);
$time = 9;
echo "<tr>";
echo "<td>" . $count . "</td>";
while($time <= 16){//time begins at 9 and stops at 16. Would be better to get this from the db too.
if((Time($row['BookingTime'])==$time)){
echo "<td style='background-color:lightCoral'>X</td>";
$row = mysql_fetch_assoc($result);
}else{
echo "<td style='background-color:lightGreen'><a href='MakeBarberBooking.php?&time=" . $time. "&date=" . $_POST['selectDate'] ."'>Book</a></td>";
}
$time=$time+0.5;
}
echo "</tr>";
}//end while
//end if submit pressed
?>
</table>
</form>
</body>
</html>
<?php
ob_end_flush( );
?>
the system loops through each time slot using the time=time+0.5 but that records the time as 10.5 instead of 10:30 for instance
Besides that ProEvilz already commented about Sql Injection, adding .5 will not magically make it into a date/time format.
Work with the date object (or DateTime class in php5.4+) and for each iteration you use this:
Initial value would be
$currentTime = "09:00";
$nextTime = date("H:i", strtotime($currentTime ." +30 MINUTE"));
$nextTime would be 09:30..
You could use PHP's DatePeriod function.
First create the start and end times. Then create a date interval and loop over the object.
N.B. its worth noting you may need to add the interval to the dtEnds to get the loop to include the last period.
// set format the date string is formatted as
$format = 'Y-m-d H:i:s';
// set the start and end date
$dtStarts = new DateTime();
$dtEnds = new DateTime::createFromFormat($format, '2017-12-01 06:00:00');
// create intervals that we would like to loop over
// i.e. 1 day at a time, or every 45 minutes
$dtInterval = DateInterval::createFromDateString('1 days');
$dtIntraDayInterval = DateInterval::createFromDateString('45 minutes');
// set day period/range
$dpPeriod = new DatePeriod( $dtCalStarts, $dtInterval, $dtCalEnds );
// loop oveer each period in the day
foreach ( $dpPeriod as $dtDay ){
echo "<pre>";
var_dump($dtDay);
echo "</pre>";
}

How to alter CSS properties using PHP based on a conditional

I'm working on a website that manages food. Keeping track of expiration dates and the such.
When a users dashboard loads, it shows a list of the food items they've currently added along with info about them, Brand, Location (Fridge,Pantry,Freezer), and expiration date.
I have the items in a html table, drawing their values from php echos of the rows of a food table I created.
What I want to do is change the text of the expiration date to red when there is about a 3 day difference between the current date and the set expiration date.
Here's my code for putting the values in the table.
<?php
while($rows = mysql_fetch_array($sql2))
{
?>
<tr>
<td><b><?php echo $rows['Name'] ?></td>
<td><b><?php echo $rows['Brand'] ?></td>
<td><b><?php echo $rows['Type'] ?></td>
<td><b><?php echo $rows['Container'] ?></td>
<td><b><?php echo $rows['ExpirationDate'] ?></td>
</tr>
<?php
}
?>
$sql2 holds a query of all the foods owned by the user.
So how would I create a conditional that would make this work out?
$date1 = new DateTime("now");
$date2 = $rows['ExpirationDate'];
$difference = $date1->diff($date2);
$days = $difference->d;
$class = '';
if ($days <= 3)
$class = 'class="expired"';
Then add the $class variable to each table cell. If the difference between dates is 3 days or less, it will add class="expired" otherwise it will add nothing. Then just style the .expired class to have red text.
You will most likely have to format your $date2 variable, but how to do that depends on the format it's currently in...
You can assign a different class to the expiration date when it's getting close.
Something like:
<td><b><?php
$exptime = strtotime($rows['ExpirationDate']);
if ($exptime - time() < 3*24*60*60){
$class = 'expBad';
}else{
$class = 'expOK';
}
echo "<span class=\"$class\">".$rows['ExpirationDate']."</span>" ?></td>
Then in your .css you can define the class expBad to be red.
span.expBad {
color: red;
}

query between range of dates not showing results

I have a mysql database with a field called DATE, storing data as a date. I am trying to get the php date to select records for the next 31 days from the current date.
This is what I have...
$start_THISMONTH = "-1";
if (isset($to_date)) {
$start_THISMONTH = $to_date;
}
$finish_THISMONTH = "-1";
if (isset($from_date)) {
$finish_THISMONTH = $from_date;
}
mysql_select_db($database_WHTSON, $WHTSON);
$query_THISMONTH = sprintf("SELECT * FROM CALENDAR WHERE DATE BETWEEN %s AND %s AND APPROVED = 1 ORDER BY DATE ASC", GetSQLValueString($start_THISMONTH, "date"),GetSQLValueString($finish_THISMONTH, "date"));
$THISMONTH = mysql_query($query_THISMONTH, $WHTSON) or die(mysql_error());
$row_THISMONTH = mysql_fetch_assoc($THISMONTH);
$totalRows_THISMONTH = mysql_num_rows($THISMONTH);
-
The code to set up the two variables is
$from_date = date("Y-m-j");
$to_date = date('Y-m-j', strtotime("+31 days"));
And my php code in the body is
<h4><strong><font color="#FF0000"><?php echo $row_THISMONTH['EVENT_NAME']; ?></font></strong></h4>
<?php $date = date_format($row_THISMONTH['DATE'], 'jS F'); ?>
<h5><em><?php echo $date; ?>, <?php echo $row_THISMONTH['TIMES']; ?><br />
<?php echo $row_THISMONTH['LOCATION_ADDRESS']; ?>, <?php echo $row_THISMONTH['LOCATION_TOWN']; ?> <?php echo $row_THISMONTH['LOCATION']; ?></em><br />
</h5>
<p><?php echo $row_THISMONTH['EVENT_DETAILS']; ?><br />
</p>
No results are showing up. This is a new build database, and only one record is in there, with a date of Valentines Day. If I change the code to a simple "find all records" query it shows up great (though the date_format doesn't display a date.
This is my nemesis, please help me understand what I've done wrong?
If you have a date field column in mysql(YYYY-MM-DD) then try date('Y-m-d') instead of date('Y-m-j')
I have been staring at this for so long, but I think I have found one answer. I tried to be logical and use $to_date and $from_date, and then put them in the wrong order in the query. So although I haven;t actually solved the issue, I thinnk the issue is my untidyness on this occasion. I learnt a lot from the discussion too, thank you very much - time for a cleen sheet and a slower pace :)

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>";

MYSQL ordering columns in my query

I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.
<?php
require 'connect.php';
?>
<h3>Monthly Finances | Add New Month </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}
?>
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];
echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";
if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];
echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>
My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.
Do your tables contain an index/id?
You can easily order them in ascending/descending by "ORDER BY"
ALTER TABLE `table_name` ORDER BY `id`
Note default ORDER BY is in ascending order. Put DESC at the end if you want descending.
If you want your mysql query to output results in a nice ordered fashion, you can also use ORDER BY in the query:
$gathermonths = "SELECT `month`, `year` FROM `month` ORDER BY `month` DESC";
There is also GROUP BY functions in case you wanted to group your results by month:
$gathermonths = "SELECT `month`, `year` FROM `month` GROUP BY `month`";
Instead of the DESCRIBE query, you could use mysql_fetch_field. Then columns will always be in the same order you have on your SELECT:
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
// Loop the columns to build the table headers
echo '<table>';
echo '<tr>';
while ($i < mysql_num_fields($query_run)) {
$field = mysql_fetch_field($query_run, $i);
echo '<th>' . $field->name . '</th>';
$i++;
}
echo '</tr>';
// Your current data loop
while($row = mysql_fetch_assoc($query_run)){
// (...)
}
echo '</table>'
}
?>
Since you're already specifying which columns you're fetching, simply output the column headers explicitly rather than querying the database.
Contrariwise, if you want to abstract the HTML table generation code so that it works with arbitrary SQL tables (thus separating data access from display), record the column names as you generate the column headers in an array, then iterate over this array when outputting rows. You can also do away with the $rent = $row['rent']; assignments, as they gain you nothing. Using PDO:
/* data access */
$finances = $db->query('SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month`');
$columns = array();
for ($i = 0; $i < $finances->columnCount(); ++$i) {
$meta = $finances->getColumnMeta($i);
$columns[$meta['name']] = ucwords($meta['name']);
}
/* data display. Note this is completely independent of the type used to store
the colum & row data. All that matters are that $columns and $finances are
Traversable
*/
?>
<table>
<thead>
<tr>
<?php foreach ($columns as $name => $label): ?>
<th><?php echo $label ?></th>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach ($finances as $monthly): ?>
<tr>
<?php foreach ($columns as $name => $label): ?>
<td><?php echo $monthly[$name]; ?></td>
<?php endforeach ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Error handling and abstraction into modules left as an exercise.

Categories