MYSQL - Selecting Dates of Current Work Week - php

I'm am writing a PHP program that will get all of the dates for the current work week (excluding Monday). My code is as follows:
//Get Year
$sql = "SELECT YEAR(CURDATE()) AS CurYear";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curyear = $row['CurYear'];
//Get Week
$sql = "SELECT WEEK(CURDATE()) AS CurWeek";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curweek = $row['CurWeek'];
//Get Date of Tuesday
$sql = "SELECT STR_TO_DATE('$curyear$curweek Tuesday', '%X%V %W') AS TueDate";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tuedate = $row['TueDate'];
It works and will return the date of this Tuesday, but is there a more efficient way of doing this, and moreover doing it for the following 3 days?

As explained here: How to find the day of week from a date using PHP?
you can use the date command:
$time = time(); // present time
$day = 3; //the day of the week we are looking for 0: sunday, 1 monday and so on
$dayofweek = date('w', $time); //current day week number
$result = date('Y-m-d', strtotime(($day - $dayofweek).' day', $time));

I'm not sure if you have a requirement of using MySQL, but I would do this in PHP directly. Below is a sample of how you could approach it. Once the variable $TuesTS is set, you can figure out the next day by adding (24*60*60) or 86400 to it, which is the number of seconds in a day.
<?php
$ts = time();
$todayNum = date('N');
if ( ($todayNum >= 2) && ($todayNum<=5)){
$offset = $todayNum - 2; // number of days after Tuesday;
$TuesTS = $ts-($offset*24*60*60);
echo "Tuesday : ".date('Y-m-d', $TuesTS);
}
?>

Related

Issue displaying correct week from MySQL database

I have a expenses script that displays the current week by week number based on week number in the database (w10) and can select other weeks by using ?selectWeek=w46
We have been using this script for a year now and does not show the information for this week (w10) because there are 2 entries in the database for w10 and it's getting confused which one to display.
Database Structure
ID - Base_Charge - Week - Year - Created_ At
1 - 20000 - w10 - 2021 - 2021-03-08
53 - 454333 - w10 - 2022 - 2022-03-07
Code:
<?php
include '../main.php';
check_loggedin($pdo);
// output message (errors, etc)
$msg = '';
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge');
$stmt->execute();
$weekList = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_GET['selectWeek'])){
$week = $_GET['selectWeek'];
}else{
$ddate = date('y-m-d');
$date = new DateTime($ddate);
$week = 'w'.$date->format("W");
}
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ?');
$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare('SELECT * FROM expense where week = ?');
$stmt->execute([$base_charge['id']]);
$expense = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
Any idea how to make it view the correct week please?
When you want select only current year records you can improve your where statement in next way:
$week = 'w10';
$stmt = $pdo->prepare(
'SELECT * FROM expense_base_charge WHERE week = ? AND year = YEAR(NOW())'
);
$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
PHP MySQL Feddle
Another way, you can calculate default week/year values in PHP
(in next example I also changed week column format to int)
//set current week/year values when they not provided by GET
$week = $_GET['selectWeek'] ?? date('W');
$year = $_GET['selectYear'] ?? date('Y');
//debug only print
printf('YEAR: %d, WEEK: %d ' . PHP_EOL, $year, $week);
//select data fom MySQL using week & year
$stmt = $pdo->prepare(
'SELECT * FROM expense_base_charge WHERE week = ? AND year = ?'
);
$stmt->execute([$week, $year]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
Test online
The problem is that you are storing the value for week and year in a denormalized form. The week number should not be stored with prefix w. Ideally, you would store both of them in a single column. Then you could use YEARWEEK() function in SQL.
This is of course assuming that you are using ISO 8601 week numbering. If you are not following this scheme then fetching the correct value will be very difficult.
If you don't want to change the table schema now, you can still get the same value using PHP. Use 'o' for year number and 'W' for week number.
$week = $_GET['selectWeek'] ?? 'w'.(new DateTime())->format("W");
$year = $_GET['selectYear'] ?? (new DateTime())->format("o");
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ? and year = ?');
$stmt->execute([$week, $year]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);

Add 3 days to date fetched from DB expecting weekends

I have a table with a status column and date column. I need to add 3 days to my date from the DB expecting weekends if status is 2 or 6. Here is my code:
$selectall = sqlsrv_query($conn, "select * from Table where and Status = 2 or status = 6", $params, $options);
while($fetchall = sqlsrv_fetch_array($selectall))
{
$id = $fetchall['DATAID'];
$dates = $fetchall['DATE'];
if( 3 DAYS PAST )
{
sqlsrv_query($conn, "UPDATE TABLE SET STATUS=5 WHERE DATAID=$ID")
}
}
I don't see how is this a JS question, but anyhow, you need to calculate date range in your php code and put that date range into your SQL query. AKA you take the start date, check which weekday it currently is and do respective mathematical calculations to add additional days.
I would use something like this around my date variable
select
DATEADD(d,
case when datepart(dw,'2017-05-17')=6 then 6
when datepart(dw,'2017-05-17')=7 then 5
when datepart(dw,'2017-05-17')=1 then 4
when datepart(dw,dateadd(d,3,'2017-05-17'))=7 then 5
when datepart(dw,dateadd(d,3,'2017-05-17'))=1 then 4
else 3
end
,'2017-05-17')
$selectall = sqlsrv_query($conn, "select * from Table where and Status = 2 or status = 6", $params, $options);
while($fetchall = sqlsrv_fetch_array($selectall))
{
$DATAID= $fetchall['DATAID'];
$dates = $fetchall['DATE'];
$p = date("l");
switch ($p)
{
case "Wednesday" || "Thursday" || "Friday":
$day = '-5 days';
break;
default:
$day = '-3 days';
}
$s = date($dates);
$today = date('Y-m-d');
$totalday = date('Y-m-d', strtotime($day));
if($totalday <= $s)
{
sqlsrv_query($conn, "UPDATE table SET STATUS = 5 WHERE DATAID=$dataid");
}
}

PHP Check if 10 minutes has gone by

I want to compare two dates with each other to see if 10 minutes has passed.
This is the code that I've got but I can't quite figure out how to do it.
I get the first date from my table (which is saved as a timestamp, example: 2017-03-26 22:33:45) and then I want to compare it with the time that is right now.
$sql = "SELECT saved_time from table1 where email = '$email'";
$stmt = $conn->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch()) {
$savedTime = $row[0];
}
$now = time();
if (/*10 minutes has passed between saved time and now*/) {
echo "Your account is unlocked";
} else if (/*10 minutes hasn't passed*/) {
echo "Your account is locked";
}
Try This code:
$timezone = "Asia/Kolkata";// Select Timezone as of your Preference or MySQL Server Timezone
date_default_timezone_set($timezone);
$sql = "SELECT saved_time from table1 where email = :email";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $email));
while($row = $stmt->fetch()) {
$savedTime = $row[0];
}
// Uncomment below Line if $savedTime is in MySQL DATETIME Format
// $savedTime = strtotime($savedTime);
$now = time();
if (round(($now - $savedTime) / 60,2) >= 10){
echo "Your account is unlocked";
} elseif (round(($now - $savedTime) / 60,2) < 10){
echo "Your account is locked";
}
if $now = time(); #(this will generate a timestamp)
assuming $savedTime = $row[0]; is a MySQL date field, you can do
$savedTimeTimestamp= date("Y-m-d H:i:s", $savedTime);
...now 10 time 60 seconds is 10 minutes, so
if ($now > ($savedTimeTimestamp+600))
should do the job
If mysql solution is fine for you, then
select * from table T where TIMESTAMPDIFF(MINUTE,.saved_time,NOW()) > 10
If you need it in php, then
$db_time = $row['saved_time'];//as you have stored in timestamp already
$curr_time = strtotime(date('Y-m-d H:i:s'));
$diff = round(abs($db_time - $curr_time) / 60,2);
if($diff > 10)
Update
select now() as curr_time, saved_time from table where COND;
then in php
$diff = $curr_time-$saved_time;
if($diff > (10*60 ))
I am not sure whether this will work. But just an idea.

Echo date december 2015

I am using below jQuery:
$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '".date("Y-".(date("m")-1)."-01")."' AND '".date("Y-".(date("m")-1)."-31 23:59:59")."' ";
This works fine, where previous month is in the same year as current date.
But now I run into trouble, because can't echo december, which is different year (2015) than january (2016).
Is there any elegant solution?
You can use strtotime function to get previous month date, pass that time value to date function as second argument like date("Y-m-d", strtotime("today -1 month")), also to get the last date of any month by changing the date format in date function argument, e.g. to get last date of previous month you can use date("Y-m-t", strtotime("today -1 month")).
So, in your case, try this:
$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '". date("Y-m-01", strtotime("today -1 month")) ."' AND '".date("Y-m-t", strtotime("today -1 month")) ."' ";
$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '".date("Y-m-01", mktime(23, 59, 59, date("n")-1, date("j"), date("Y")))."' ";

PHP/MySQL check for ip if availabe in past 24 hours using time()

Database:
pub_id pub_name time ip
1 King 1359500087 3388636152
2 Queen 1359550082 6385394932
3 Jack 1359502084 5648646562
4 Heart 1359524083 9283834142
5 Jim 1359503082 3388636152
|_ Using time() |_ Using ip2long()
PHP/MySQLi Code:
$pub_id = $_GET['pub_id'];
$pub_name = $_GET['pub_name'];
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$time = time();
$query = $db->query("SELECT * FROM impressions WHERE pub_id = '$pub_id' AND pub_name = '$pub_name' AND ip = '$ip' AND time >= '???'");
$ip_adderss = $query->num_rows;
$query->close();
if($ip_adderss == 0){
// Redirect
} else{
// Do nothing
}
Now using the time() and IP how can i check that the current visitor last visit was 24 hour ago or not?
A simple solution is using if statement to check the ip time and now time.
// Check if the IP is new or returning
$query = $db->query("SELECT * FROM impressions WHERE pub_id = '$pub_id' AND pub_tag = '$pub_tag' AND month = '$month' AND day = '$day' AND ip = '$ip' AND domain = '$domain' AND valid = '1' ORDER BY id DESC");
$ip_address = $query->num_rows;
if($ip_address == 0){
$ip_ok = 1;
} elseif($ip_address != 0){
$impression = $query->fetch_assoc();
if($time >= ($impression['time'] + 86400)){
$ip_ok = 1;
} else{
$ip_ok = 0;
}
} else{
$ip_ok = 0;
}
Your time field contains unix timestamp, which is just a number of seconds.
So, it's easy to calculate a point that lies a day ago - just subtract 86400 from the current timestamp.
So, your condition is going to be as simple as an elementary school math:
WHERE time >= unix_timestamp() - 86400
or, if you want it using time() PHP function
$time = time() - 86400;
$query = "SELECT * FROM impressions WHERE ... AND time >= ?");
and then bind that value.

Categories