Add 3 days to date fetched from DB expecting weekends - php

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

Related

MYSQL - Selecting Dates of Current Work Week

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);
}
?>

Adding 2 days and comparing

I've written some code to check if 2 days have passed using 2 dates, but it does not seem to work.
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT * FROM Reservering";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$res = strtotime($row['ReserveringsDatum']);
echo date('d-m-y', $res);
}
mysqli_close($_connection);
?>
$row['ReserveringsDatum'] is a date which looks like this: "07-01-14" (example).
For some reason the echo date('d-m-y', $res); shows me "14-01-07", which is just the day and year being reversed.
Edit:
For those wondering how it ended up, here is the working code:
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2 ";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['Betaalt'] == 'nee') {
$query2 = "DELETE FROM Reservering WHERE `ReserveringID` = '".$row['ReserveringID']."'";
mysqli_query($_connection, $query2);
}
}
mysqli_close($_connection);
?>
As said in the comment, i would make the selection within SQL. There is not need selecting all the rows and filter them in PHP. Its something better done in SQL.
Simple Example:
SELECT *, DATEDIFF(NOW(), ReserveringsDatum) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Make sure reserveringsdatum is a DATE, if its a TIMESTAMP you need to convert it to DATE.
SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Try this
$res = strtotime($row['ReserveringsID']);
$limit = strtotime($row['ReserveringsID']) + strtotime("+2 day", $res);
var_dump($res); var_dump($limit);
if($limit > $res) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
I think you need to fix you're condition.
If you want to check if $res is more than two days you have to compare limit to the current time, instead of $res.
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
if($limit < time()) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
Your problem is in this line
$limit = strtotime($row['ReserveringsID']) + $2days;
You need to add 2 days like this one
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
Working demo of adding 2 days to a date
https://eval.in/86632
How do I add 24 hours to a unix timestamp in php?
Adding days to a timestamp

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.

Updating a mysql database based on case statements

I really need help on this one. I'm trying to do a mysql update based uisng case but i don't think i'm getting it right.
Here is what i'm trying to achieve.
I have a table with the following fields
user_id, rank, weekly, monthly, justwinners
1 9 0 0 0
2 29 0 0 0
3 8 0 0 0
4 10 0 0 0
5 12 0 0 0
What i want to achieve is to update the weekly, monthly and justwinners fields based on specific dates
Lets say i have a start date of 5/07/2011.
$startdate = 5-07-2011;
At the end of one week which is 12/07/2011 i want to update the weekly field of the user with highest rank to 1. Also at the same time update justwinners
field of the next 3 users with the highest rank to 1.
At the end of the second week which is now 19/07/2011, i want to update the weekly field of the user with highest rank whose value is still '0' to 2 and also update
the justwinners field whose value is still '0' to 2.
This will continue until i get to one months time when i will update the monthly field.
This is what i have been able to come up with so far which is not working.
//Initiate the database connection here
function get_db_conn() {
$conn = mysql_connect(HOST, DB_USER, DB_PASSWORD) or die('Could not Connect!');
mysql_select_db(DATABASE, $conn) or die ('could not connect to database');
return $conn;
}
function updateWinners( $limit, $field ) {
$conn = get_db_conn();
switch($field) {
case "weekly" :
$limit = 1;
case "monthly" :
$limit = 1 ;
case "giftpack" :
$limit = 10 ;
default:
$limit = 1 ;
}
$sqlquery = "SELECT * FROM application rank DESC " ;
$sqlquery .= " where $field < 1 ";
$sqlquery .= " LIMIT $limit ";
$result = mysql_query($sqlquery);
$user_data = mysql_fetch_row($result);
if(isset($user_data)) {
$user_data = 0 ;
while($user_data){
$uid = $user_data(user_id);
$rank = $user_data(rank);
$query = "INSERT INTO application_winners (user_id, rank, date) VALUES ('$uid', '$rank' 'now()')";
mysql_query($query) or die('Error, insert winners query failed');
switch ($action) {
case "weekly":
$startdate = "5-07-2011";
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN weekly = '1'
WHEN (CURDATE() = (startdate * 14))
THEN weekly = '2'
WHEN (CURDATE() = (startdate * 30))
THEN weekly = '3'
ELSE weekly
END";
}
$user_data = $user_data + 1;
} //endwhile
}
else {
echo "Error in updating the winners";
}
}
In case you know of any better way to implement this. kindly share.
Just as a remark - you have an insert followed by an update. You could do this in the insert part. Something like:
$query = "INSERT INTO application_winners (user_id, full_name, rank, date, $field) VALUES ('$uid', '$user_fullname', '$rank' 'now()', '$updatevalue')";
mysql_query($query) or die('Error, insert winners query failed');
i did not look at everything closely but you are using the variable "$action" for the second switch but it does not exist anywhere else in your code..
Try changing:
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN weekly = '1'
WHEN (CURDATE() = (startdate * 14))
THEN weekly = '2'
WHEN (CURDATE() = (startdate * 30))
THEN weekly = '3'
ELSE weekly
END";
to:
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN '1'
WHEN (CURDATE() = (startdate * 14))
THEN '2'
WHEN (CURDATE() = (startdate * 30))
THEN '3'
ELSE weekly
END";

Select last record from same day

Heres the problem...
I have a loop looking like this selecting stuff from my database.
$query = "SELECT * FROM table WHERE publish <= CURDATE() AND active = 'Yes' AND (YEAR(begin) = YEAR(CURDATE()) OR YEAR(begin) = YEAR(CURDATE()) + 1) ORDER BY begin ASC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['begin'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',strtotime($timePeriod));
$timePeriodM = date('F',strtotime($timePeriod));
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodY = date('Y',strtotime($timePeriod));
if ($timePeriodY == $thisYear){
}
else if ($timePeriodY == $nextYear){
}
echo '<h2 class="year>'.$timePeriodY.'</h2>';
echo '<ul class="column">';
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodMonth = date('Y',strtotime($timePeriod));
if ($timePeriodY == $timePeriodMonth) {
$moSe = strftime('%B',strtotime($timePeriod));
$MonthSe = ucfirst($moSe);
$seMonth = str_replace($dateSearch,$dateReplace,date('F',strtotime($timePeriod)));
echo $seMonth;
foreach ($newsItems as $item)
{
$ad_event = date("Y-m-d",strtotime($item['event_end']));
$today = date("Y-m-d");
$dayMod = strftime('%e',strtotime($item['event_begin']));
$seDay = str_replace($dateSearch,$dateReplace,date('D',strtotime($item['event_begin'])));
echo ''.$seDay.' '.$dayMod.' - '.$item['event_title'].'';
echo '</div>';
}
}
}
}
}
else
{
echo '';
}
This code outputs the data for each row and separates it for year month day etc. However some of the data is on the same day. Thats fine BUT when data is on the same day i want a variable that holds only the last of the items on that same day.
EX.
DB
PUBLISH ID NAME
2011-05-05 1 test 1
2011-05-05 2 test 2
2011-05-06 3 test 3
The result I would like from this is something like this
RESULT
test 1 ID 1 PUBLISH 2011-05-05 VARIABLE 2 <<-- see the variable that comes from test 2 row
test 2 ID 2 PUBLISH 2011-05-05 VARIABLE 2
test 3 ID 3 PUBLISH 2011-05-06 VARIABLE 3
Meaning test 1 in this case holds information about test 2 since test 2 is after test 1 and they both have the same date. If there is only one on the specific date as test 2 and 3 just echo the same id as the variable.
Any ideas? PLease tell me if i need to explain this even more :)
Thanks a lot for any help!
Group by date(begin)as you want only 1 record on the same date(begin) and since you want the latest order by dsc on column 'begin' (I believe the 'begin' is stored as datetime else you need to have dsc on table.ID)
$query = "SELECT *
FROM table
WHERE publish <= CURDATE()
AND active = 'Yes'
AND (YEAR(begin) = YEAR(CURDATE())
OR YEAR(begin) = YEAR(CURDATE()) + 1)
GROUP BY begin
ORDER BY begin DSC";

Categories