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

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

Related

else statement not triggering else

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!

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

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.

how to use if conditions for post request data in php

I have three input boxes in html:
<input type='text' name='source' />
<input type='text' name='target' />
<input type='text' name='date' />
<input type='submit' name='submit' value='go' />
In this, i am successfully retrieved source and target data from mysql but if date is not supplied then i have to retrieve last 7 days data from database. I can try this, and created a function for select query but use seven variables and structured them in table form. Problem is i can't design a suitable logic for all of this like,
retrieve seven days data of source if date is not suppplied retrieve
seven days data of target if date is not suppplied
I can try this using if and elseif condition like:
if (isset($_POST['source']) && empty($_POST['target'] && empty($_POST['date'] ) {
//fired query function seven times with different dates through pass a query
$init->get_result( $_POST['source'], date('Y-m-d') );
}
function for select_query:
function get_result() {
$query = "select count(*) from tablename where column=$_POST['source']";
$this->select_query($query); //from there select query function called
}
function select_query($post, $date) {
$res = $mysqli->query($query);
$row->$res->fetch_row();
return $row[0];
}
And if date is supplied then data is retrieved for specific date, all this done well but not logic well. Also i am using form action as php_self to get an result on same page, but when i am using result in variable and show in html table then i have to given a condition that after specify post data result is show, which is not done. This is so lengthy, but problem is very critical for me. Please have a look on this.
Update: I get values from database in php in this code:
if ( !empty( $_POST['source'] ) && empty( $_POST['target'] ) && empty( $_POST['date'] ) ) {
echo '<table border=1>';
echo '<tr>' . '<td>' ."<input type=submit name='tod' value=" . date( 'Y-m-d' )." >" . '</td>' . '<td>' . $adinit->get_req_data( $_POST['source'], date( 'Y-m-d' ) ) . '</td>' . '</tr>';
}
I am created a input button in echo statement, which shows date. I am trying to create an event on button which shows another tabular data from database. How can i do this?
You can use strtotime() function:
if (isset($_POST['source']) && empty($_POST['target'] && empty($_POST['date'] ) {
$time = strtotime('-7 days'); // or strtotime('-1 week') works too
//fired query function seven times with different dates through pass a query
$init->select_query( $_POST['source'], date('Y-m-d', $time) );
}
Appendix:
In order to work with time interval of one day you have to change your query to something like this:
get_req_data($source, $date) {
$dateMax = date('Y-m-d', strtotime($date) + (60 * 60 * 24)); // + 1 days
$query = "Select count(*) from tablename where time >= '$date' AND time <= '$dateMax'";
...
}
This will only work if time column is of datetime/timestamp type.

Displaying results depending on its date (month & year)

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

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