how to use if conditions for post request data in php - 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.

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 do I use a form to change the SQL query to only display registered dates between a specific range?

The code below is what I have so far, if anyone has any knowledge of how BETWEEN works and could point me in the right direction I would really appreciate it.
<form action="index.php" method="GET">
Starting from:<br>
<input type="date" name="startDate" ><br><br>
Upto:<br>
<input type="date" name="uptoDate" ><br><br>
<input type="submit">
</form>
<?php
// I removed the connection details for obvious reasons
// It does connect and display the data with no problems
$startingFrom = $_GET[startDate];
$upto = $_GET[uptoDate];
// I tried this but it does not seem to work
// $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
$query = "SELECT * FROM table";
$result = mysql_query($query);
echo "<table><th>Name</th><th>Registered Date</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['registered'] . "</td></tr>";
}
echo "</table>";
mysql_close();
?>
If you are returning results between two given dates use this code
SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03' AS DATE) AND CAST('2015-05-28' AS
DATE);
With BETWEEN with dates you need to use CAST() to convert the value to appropriate datatype such as DATE or DATETIME. If you are using BETWEEN with DATETIME cast your value to DATETIME:
SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03 08:40:09' AS DATETIME) AND CAST('2015-05-28 02:50:09' AS DATETIME);
As a side note, use MySQL improved extension (mysqli) and you are forgetting to close your input fields which is not a good code.
Your query should be:
select * from table where registered >= $startDate and registered <= $endDate;

Posting a form with mysqli

I've created a web page working with php and mysqli in which I can send and edit MySQL entries without errors. The entries have title and date. The problem, appears when I try to change a date that is NULL.
Create an entry with date: Works
Create an entry without date: Works
Edit an entry with a date: Works
Edit an entry with a date to NULL: Works
Edit an entry with date NULL to an existing date: (doesn't work)
I've tried and tested things and I can assume that the problem is that the "day", "month" and "year" inputs are in blank/empty when the form is generated by PHP.
Also can't understand why the form to create an entry, which is exactly the same but with all the inputs in blank at the beginning, works in every case.
This is how I generate my form:
$mysqli->set_charset('Latin1');
$id=$_POST["id"];
$res = $mysqli->query("SELECT * FROM `list` WHERE `id`=$id");
while($row = $res->fetch_assoc()) {
if ($row["fecha"]==NULL) {$day="";$month="";$year="";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "
<div class='home'>
<form accept-charset='Latin1' method='post' action='http://mypage.com/?opt=list&f=view'>
<input type='text' value='".$row['title']."' name='title' id='title' required><br>
<input type='number' value=".$day." name='day' id='day' min='1' max='31' placeholder='day'>
<input type='number' value=".$month." name='month' id='month' min='1' max='12' placeholder='month'>
<input type='number' value=".$year." name='year' id='year' placeholder='year'>
<input style='display:none;' type='number' value=".$id." name='id' id='id' placeholder='id'>
<input type='button' id='datepicker'><br>
<input type='submit' name='edit' value='Update'>
</form>
</div>";
};
And this is what happens when I submit:
$edit=$_POST["edit"];
if ($edit) {
$id=$_POST["id"];
$title=$_POST["title"];
if (empty($_POST["year"])&&empty($_POST["month"])&&empty($_POST["day"])){
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=(NULL) WHERE `id` = $id;");
}else{
$date=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=('$date') WHERE `id` = $id;");
};
print ("Entry updated to ".$date); //When it doesn't works nothing appears in $date
};
I don't have any kind of idea of why it doesn't work JUST when the "day", "month" and "year" inputs are empty at the beginning.
PS. This is a solution (when date is NULL give values and then clear them when the form is generated), but I still don't know what is the problem with the inputs:
...
if ($row["fecha"]==NULL) {$day="0";$month="0";$year="0";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "...";
if ($row["fecha"]==NULL){echo "<script>document.getElementById('day').value='';document.getElementById('month').value='';document.getElementById('year').value='';</script>";
...
Thanks to any help.
When you submit form, empty values from inputs are not submitted as null. They are submitted as empty string "" or zero in case of input which type is number.
Best way to avoid this is to use empty() function:
if (empty($_POST["year"]) && empty($_POST["month"]) && empty($_POST["day"])) {
// code ...
}
This function returns true when the variable is null, zero, false or empty.
Updated answer:
If you can't edit null date column to some date, make sure that:
That the column type of DATE
That your variables that contain year, month and day are formatted with precending zeros
Wrong examples: day = 5, month = 9
Good examples: day = '05', month = '09'
When you concate them as integers you get '2016-9-5' which is invalid date format.
So you should format them as strings with precending zeros like this '2016-09-05'.
Change this line of code:
$date=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
To:
$date=sprintf("%04d-%02d-%02d", $_POST["year"], $_POST["month"], $_POST["day"]);
(Posted on behalf of the OP).
The problem was just syntax errors:
value= ' ".$day." '

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/PHP update query with dates not updating

Bit of a strange problem here...
I've got an update query that isn't working, and I can't for the life of me work out why!
My table has two three fields - 'id' (int, auto increment), 'date' (date), and 'amountraised' (decimal). Part of the app I'm developing calculates the fundraising total each week made by a charity bookstall. The 'date' field uses a date column type as elsewhere on the site I'm using the dates in calculations.
Elsewhere within the system I've got other update queries that are working just fine, but I suspect the problem with this one is that as well as updating the record I'm also trying to manipulate the date format as well (so that I can enter dates in the British dd-mm-yyyy format and then use the PHP to convert back into the MySQL-friendly yyyy-mm-dd format.
This is the strange bit. According to the confirmation page on the site, the query has run okay, and the update's been made, but when I check the database, nothing's changed. So I could check what the output of the query is I've tried echoing the result to the web page to see what I'm getting. The expected values show up there on the page, but again, when I check the database, nothing's been updated.
This is my update form with the date conversion function:
function dateconvert($date,$func) {
if ($func == 1){ //insert conversion
list($day, $month, $year) = split('[/.-]', $date);
$date = "$year-$month-$day";
return $date;
}
if ($func == 2){ //output conversion
list($year, $month, $day) = split('[-.]', $date);
$date = "$day/$month/$year";
return $date;
}
} // end function
require_once('/home/thebooks/admins/connect.php');
$id = $_GET['id'];
$dateinput = $_GET['dateinput'];
$query = "SELECT * FROM fundraisingtotal WHERE id='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
extract($row);
$date = $row['date']; //your mysql date
$realdate = dateconvert($date,2); // convert date to British date
$amountraised = stripslashes($amountraised); //amount raised
mysql_close();?>
<div id="title">Update Fundraising Total</div>
<form id="updatetotals" action="updated.php" method="post">
<div class="row"><label for="dateinput" class="col1">Date </label><span class="col2"><input id="dateinput" name="dateinput" type="text" size="25" value="<?php echo $realdate ?>" maxlength="10" /></span></div>
<div class="row"><label for="amountraised" class="col1">Fundraising Total </label><span class="col2"><input id="amountraised" name="amountraised" type="text" size="25" value="<?php echo $amountraised ?>" maxlength="7" /></span></div>
<div class="submit"><input type="submit" name="submitted" value="Update" /><input type="reset" name="reset" value="Clear the form" /></div>
<input type="hidden" name="id" value="<?php echo $id ?>" />
</form>
...and this is the form processing/query page:
require_once('/home/thebooks/admins/connect.php');
$dateinput = $_POST['dateinput'];
// Date conversion from: http://www.phpbuilder.com/annotate/message.php3?id=1031006
// using type 1
$convdate = $_POST['dateinput']; // get the data from the form
$convdate = dateconvert($convdate, 1); // Would convert to e.g. 2005-12-19 which is the format stored by mysql
function dateconvert($convdate,$func) {
if ($func == 1){ //insert conversion
list($day, $month, $year) = split('[/.-]', $convdate);
$date = "$year-$month-$day";
return $date;
}
if ($func == 2){ //output conversion
list($year, $month, $day) = split('[-.]', $convdate);
$date = "$day/$month/$year";
return $date;
}
}
$date = "$convdate";
$amountraised = $_POST['amountraised'];
$update = "UPDATE fundraisingtotal SET date = '$date', amountraised = '$amountraised' WHERE id='$id' ";
$result = mysql_query($update);
$realdate = dateconvert($date,2); // convert date to British date
if ($result) {
echo "<p class=\"dbpara\">Thank you. Your update to the record was successful.</p>";
echo "<p class=\"dbpara\">The record has been amended to a date of <b>$realdate</b> and amount of <b>$amountraised</b>.</p>";
}
else {
echo "<p>Nothing has been changed.</p>";
}
mysql_close();
The weird thing is that the confirmation text "The record has been amended to...etc." displays exactly as expected, but when I check the database, the record hasn't been updated at all.
I'm sure it must be something I'm missing with messing with the date formats or I've got something in the wrong order, but I've tried so many different variations on this now I can't see the wood for the trees. Anyone any ideas what I'm doing wrong here?
I see some red-flags here. You are getting the date from a form and inputing it into MySQL without any form of validation - that could lead to SQL-injections.
Start by changing dateconvert function to something more secure. This function will always return a correct formated date, even if the user tries to abuse the system.
Edit 1: Forgot to put a : after case 'en_en' but fixed it now. Thanks neonblue.
Edit 2: Forgot to feed the date() function with the timestamp. Fixed!
Edit 3: A preg_replace to convert frontslashes to dashes
// this function always returns a valid date
function dateconvert($date = NULL, $date_type = 'sql') {
$date = preg_replace("/", "-", $date);
$timestamp = strtotime($date);
switch($date_type) {
default: case 'sql' : return date('Y-m-d', $timestamp); break; // prints YYYY-MM-DD
case 'en_EN' : return date('d-m-Y', $timestamp); break; // prints DD-MM-YYYY
}
}
You can always have a look into Zend_Date that will let you work with dates on your own format.
Change
$result = mysql_query($update);
to
$result = mysql_query($update) or die(mysql_error());
And you should see what the problem is when the query fails.
Three things I would look for:
Is the code attaching to the same database you are looking at? (I spent a few hours on this one ;)
Is another update statement (or this one) running immediately afterwards that would change the values back? Here you need some logging to figure it out.
If you echo the sql, what happens when you run it directly yourself?
If you see the table is not changing any value but the query does not show you any error, then WHERE id = '$id' is not hitting the register you intended to.
Don't forget to sanitize your queries as others are telling you.

Categories