Passing JS Dates() to PHP subtracts 18 hours - javascript

I want to select MySQLi records between a startdate and enddate so I have a JS script that allows me to enter dates (using HTML datebox type inputs) which I pass to a PHP script using JQuery's $.post method. My JS code is:
startDate = new Date(document.getElementById("fromDate").value);
startDate = new Date(startDate.getUTCFullYear(),startDate.getUTCMonth(), startDate.getUTCDate(), startDate.getUTCHours(), startDate.getUTCMinutes(), startDate.getUTCSeconds());
endDate = new Date(document.getElementById("toDate").value);
endDate = new Date(endDate.getUTCFullYear(), endDate.getUTCMonth(), endDate.getUTCDate(), endDate.getUTCHours(), endDate.getUTCMinutes(), endDate.getUTCSeconds());
$.post("DBQuery.php", {
startdate: startDate,
enddate: endDate,
},
function (output) {
var result = JSON.parse(output);
$('#PHPStartDate').html(result.startdate).show();
$('#PHPEndDate').html(result.enddate).show();
});
My PHP code is:
$startdate = date('Y-m-d h:i:s',strtotime($_POST["startdate"]));
$enddate = date('Y-m-d h:i:s',strtotime($_POST["enddate"]));
$con = mysqli_connect("localhost","username","password","dbase");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$visitors = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT session FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$sessions = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT country FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$countries = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT city FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$cities = mysqli_num_rows($result);
}
$output = json_encode(array("visitors"=>$visitors,"sessions"=>$sessions,"countries"=>$countries,"cities"=>$cities,"startdate"=>$startdate,"enddate"=>$enddate));
echo $output;
mysqli_free_result($result);
mysqli_close($con);
However the dates returned by PHP are 18 hours behind the dates which JS passed to PHP - very weird! My browser and MAMP server are on the same machine (my iMac) and I live in Thailand (UTC + 7 hours).
Here's a screen shot of what is displayed in HTML using the following code:
<div id="reportTitle">
Report of site activity from
<span id="startTime"></span>on<span id="startDate"></span>to
<span id="endTime"></span>on<span id="endDate"></span><br>
for<span id="showVisitors"></span>
<span id="showCities"></span>
<span id="showCountries"></span>
</div>
<div id="reportBody">
<div>
<span><h3>From</h3></span><span id="PHPStartDate"></span>
<span><h3>to</h3></span><span id="PHPEndDate"></span>
The first set of dates displayed at the top of the screenshot are simply the JS startdate and enddatevariables and the lower set of dates are those returned by the PHP variables $startdate and $enddate which ought not to have changed (but in fact are 18 hours earlier!).
Screenshot of JS and PHP dates
I suspect the problem is to do with timezones but given that Thailand is UTC+7 it's hard to work out where the 18 hour time difference is coming from.

Related

Storing a range of dates in one row in database or in seperate table

I am trying to make a car booking system using a jquery datepicker. I have the date picker, I have dates in a database(manually inserted in WAMP SERVER phpMyAdmin) that highlight those dates as pre-booked dates (Cursor disabled in css on mouse over) so you can't book those ones.
I'm at the point of assembling all my parts but have become stuck on the last bit of how to store the dates. It seems from what I've read, that storing a bunch of dates in one row is a no no (plus I haven't managed to do it).
So, should I store a start and end date for each client on the one DB table row and generate the in between dates when the page/datepicker loads?
If this approach how do I get and then join each row (many clients) of dates together?
Or should I generate the in between dates and then store all the dates in a separate table with the client id when the datepicker selects start & end?
Could someone help with the correct approach and php code to get me there. I already have the mysqli connection etc.
My DB columns at present are start_date & end_date in tabledates_from_to. My datepicker uses this format 2021-04-15 and the array needed looks like this '2021-04-15','2021-04-16','2021-04-17' to highlight the dates.
Seems like you have a 1:n relation between clients/customers and bookings. So yes you should store them in separate tables according to database normalization rules.
Assume you have a table clients (primary key client_id) and bookings, which replaces your dates_from_to table (with foreign key client_id) you can do the following JOIN:
SELECT *
FROM clients
JOIN bookings
USING (client_id)
WHERE booking_date = '2021-04-05'
For the next part I take the example array. Here is example code to insert one row for every day:
$dates = ['2021-04-15','2021-04-16','2021-04-17'];
// $pdo contains a connected DB instance
$stmt = $pdo->prepare('INSERT INTO bookings (client_id, booking_date) VALUES (?, ?)');
foreach ($dates as $day) {
$stmt->execute([1, $day]);
}
As an alternative you could use first and last day of the period and store everything in one row by replacing booking_date column by start_date and end_date.
Here is the version with mysqli and start/end date (from docs):
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->prepare('INSERT INTO bookings (client_id, start_date, end_date) VALUES (?, ?, ?)');
// iss means (i)nteger, (s)tring and (s)tring parameter
$stmt->bind_param('iss', 1, '2021-04-15', '2021-04-17');
$stmt->execute();
Hope this keeps you going.
After about a month I have the date-picker working, storing all dates in DB on their own row.
It picks a start date & end date from two datepickers.
Creates/produces all the dates in between then inserts all those separate dates into the database each date in it's own row in PHP.
Then redirects to same page & highlights all DB dates & disables them so no one can select already booked dates.
I have copied different bits of code from this site and manipulated it a little & at present I'm very happy with the hybrid outcome.
This is running on a WAMP server.
Below is my code to help other amateurs like me.
<?php
$servername = "localhost:3308";
$username = "root";
$password = "";
$dbname = "datepicker_test_outputs";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date FROM insert_datesarray";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$for_JS_date = null;
// output data of each row
while($row = $result->fetch_assoc()) {
$php_array_dates = date('Y-m-d',strtotime($row["date"]));
$for_JS_date .= "'".$php_array_dates."'".",";
$correct_date_format = substr($for_JS_date, 0, -1);
}
if($_SERVER["REQUEST_METHOD"]=="POST"){
$start_date = $_POST["from"];
$end_date = $_POST["to"];
$dateentry = array();
// populate $dateentry array with dates
while (strtotime($start_date) <= strtotime($end_date)) {
$dateentry[] = date("Y-m-d", strtotime($start_date));
$start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));
} // end while
// loop through $dateentry and insert each date into database
foreach($dateentry as $entry) {
$my_inserted_dates =("INSERT INTO insert_datesarray
(date) VALUES('{$entry}')")
or die(mysqli_error());
$result = mysqli_query($conn,$my_inserted_dates);
if($result == false)
{
echo "<script>alert('BOOKING IS NOT SUCCESS - PLEASE CONTACT ADMINISTRATOR'); </script>";
}
else
{
/* Header location to refresh the page & load booked dates */
header('Location: '.$_SERVER['PHP_SELF']);
}
} die;
// end foreach
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery UI DatePicker</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.ui-highlight .ui-state-default{
background: red !important;
border-color: red !important;
color: white !important;
cursor:not-allowed !important;
}
</style>
<script type="text/javascript" language="javascript">
var dates = [<?php echo $correct_date_format;?>];
/*var dates = ['2021-04-05','2021-04-15','2021-04-25','2021-04-30'];*/
jQuery(function(){
jQuery('input[id=from]').datepicker({
dateFormat: 'dd-mm-yy',/*CN Changes date format. Remove if required CN*/
changeMonth : true,
changeYear : true,
minDate: 0 ,/*Mindate disables dates before todays date*/
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(dates.indexOf(currDate) >= 0){
return [true, "ui-highlight", 'Date Already Booked'];
}else{
return [true];
}
}
});
})
</script>
<script type="text/javascript" language="javascript">
var dates = [<?php echo $correct_date_format;?>];
/*var dates = ['2021-04-05','2021-04-15','2021-04-25','2021-04-30'];*/
jQuery(function(){
jQuery('input[id=to]').datepicker({
dateFormat: 'dd-mm-yy',/*CN Changes date format. Remove if required CN*/
changeMonth : true,
changeYear : true,
minDate: 0 ,/*Mindate disables dates before todays date*/
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(dates.indexOf(currDate) >= 0){
return [true, "ui-highlight", 'Date Already Booked'];
}else{
return [true];
}
}
});
})
</script>
</head>
<body>
<p id="dateFrom"></p>
<p id="dateTo"></p>
<form action="" name="form1" method="post">
<label for="from">From</label>
<input type="text" id="from" name="from"onchange="getFromDate()">
<label for="to">to</label>
<input type="text" id="to" name="to"onchange="getToDate()">
<input name="book" type="submit" value="Book">
</form>
</body>
</html>

difference between given date and current date

I have a table message, in which fields are: id,username,message,lastdate. I want to compare from these dates (which are in my table) to current date. If difference is 30 days then respected username should be show in admin page.
I tried for date difference, but its not working.
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$diff=date_diff($date2,$date1);
echo $diff->format("%R%a days");
}
?>
Also I tried from this code. But nothing happend
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$query12=mysql_query("SELECT username,DATEDIFF($date1,$date2) FROM message WHERE DATEDIFF($date1,$date2)<30") or die(mysql_error());
while($result12=mysql_fetch_array($query12))
{
if($result12)
echo $username;
else
echo"record not";
}
}
?
My third solution is here. I think it is working. But It is repeating values.
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$days = (strtotime($date2) - strtotime($date1)) / (60 * 60 * 24);
$result123=mysql_query("select username from message where '$days'<30");
while($query123=mysql_fetch_array($result123))
{
if($query123)
echo $username."&nbsp".$days."<br>";
else
echo mysql_error();
}
}
?>
You can do this date comparison inside your MySQL DBMS.
Try this query:
SELECT username, message FROM message WHERE lastdate <= CURDATE() - INTERVAL 30 DAY
It should return just the rows of interest.

Disabling jQuery UI Date Picker Dates

I am trying to disable dates in a jQuery UI Date Picker, it works when I hard code the dates in to the variable in the JS file as follows:
var bookedDays = ["2015-3-7","2015-3-8","2015-3-15"];
In my PHP file I have:
<?php
$testing = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resulttesting = mysql_query($testing) or die(mysql_error() . "<br>" . $testing);
while ($rowtesting = mysql_fetch_assoc($resulttesting))
{
$from = $rowtesting['fromdate'];
$to = $rowtesting['todate'];
}
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list = array($from);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-m-d',$current_time);
}
//Finally add end date to list, array contains all dates in order
$date_list[] = $to;
$date_list_res = '["' . implode('","', $date_list) . '"]';
print_r ($date_list_res);
?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list_res); ?>;
</script>
When I run a console.log in the JS file for the variable bookedDays I get ["2015-03-05","2015-03-06","2015-03-07","2015-03-08","2015-03-08"] output which is read from the database which is correct but these dates are not disabling in the date picker. Does anybody know where I'm going wrong?
Instead of
<?php echo json_encode($date_list_res); ?>;
Type just
<?php echo $date_list_res; ?>;
Everything should be dandy.

jQuery Calender - More than one event per day

I have a calendar on my site that uses javascript/jquery to place events in the calendar. All the events are stored in a MySQL database with the title and Unix timestamp.
My problem is that this method (shown in the code below) only allows one event per day, and creating two rows with the same date, only uses the latter of the two. There are several instances where I need two or more events in one day.
My code:
var CalendarEvent = function (time, title) {
this.time = time;
this.title = title;
}
var allEvents = {
<?php require_once 'ndx/mysql.php';
$events = mysqli_query($con, "SELECT * FROM events");
while($lse = mysqli_fetch_array($events)):
$date = date('Y-m-d', $lse['timestamp']);
$notime = $lse['notime'];
if($notime != 'true'){
$time = date('g:i a', $lse['timestamp']);
}else{
$time = '';
}
$event = addslashes($lse['title']);
?>
'<?php echo $date; ?>': [
new CalendarEvent('<?php echo $time; ?>', '<?php echo $event; ?>')
],
<?php endwhile; ?>

How to loop through an array and a date range?

Here's what I need to have happen:
I have created variables that include the dates for the current week.
I have also created an array that has the sport types in it as $k => $v.
I created a javascript accordion that will open and close if clicked on. The dates of the week are used as the title of the accordion. I want to then return all the records, in their respective accordion, based on the date in the database but I also need to list those records according to sport type. So for example:
Accordion * October 2, 2013 * Accordion (when user clicks it will open and show all the records that have a game on that date listed under the sport type).
I need to echo the value of the sport type array I created if the record matches the key for the sport type. For example: if the database returns three rows of data, one having the sport type of "baseball" and two having the sport type of "MSoccer" then I need to return the records like this in a table:
BASEBALL (sport type)
VI vs. UVA close td at 6:00 PM EST
MEN'S SOCCER
VI # Montreat at 3:30 PM EST
VI vs. St. Andrews at 4:00 PM EST
if there are no records that have a game on the date then I would just echo "no games today"
Then I need to create the next accordion item and return the records for that one where the game date matches the date for the accordion.
Here's what I have so far...just not sure where to go with it:
<?php
date_default_timezone_set('US/Eastern');
$today = time();
$weekMonDate = date('Y-m-d',strtotime("last Monday", $today));
$weekTuesDate = date('Y-m-d', strtotime('+1 days', strtotime($weekStartDate)));
$weekWedDate = date('Y-m-d', strtotime('+2 days', strtotime($weekStartDate)));
$weekThursDate = date('Y-m-d', strtotime('+3 days', strtotime($weekStartDate)));
$weekFriDate = date('Y-m-d', strtotime('+4 days', strtotime($weekStartDate)));
$weekSatDate = date('Y-m-d', strtotime('+5 days', strtotime($weekStartDate)));
$weekSunDate = date('Y-m-d', strtotime('+6 days', strtotime($weekStartDate)));
$sport = array(
"Baseball" => 'BASEBALL',
"MSoccer" => 'MEN\'S SOCCER',
"MBasketball" => 'MEN\'S BASKETBALL',
);
foreach ($sport as $k => $v) {
$sql = 'SELECT gametime, conference, scrimmage, exhibition, gamedate, homeschool, visitorschool, homelivestatsurl, notes, gamestatus, homescore, visitorscore, score, record, sporttype FROM schedule WHERE WEEKOFYEAR(gamedate)=WEEKOFYEAR(NOW()) ORDER BY gamedate';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
?>
<?php
mysql_data_seek($result, 0);
$day = ' ';
$sport = ' ';
while ($row = mysql_fetch_assoc($result)) {
if (date("d", strtotime($row['gamedate'])) !== $day) {
$day=date("d", strtotime($row['gamedate'])); ?>
?>

Categories

Resources