how can i loop two colum values - mysql

I have a table named leaves.
----------
id FromDate ToDate
1 20-01-2019 22-01-2019
2 15-01-2019 22-01-2019
3 13-01-2019 20-01-2019
I want all dates between each column.
Can anyone help?

If you want to do it in your php code then you can do it by finding day count between two days and loop it to get the all dates between that two dates.
<?php
$date1 = "2019-01-13";
$date2 = "2019-01-20";
$date1 = strtotime("2019-01-13");
$date2 = strtotime("2019-01-20");
$datediff = $date2 - $date1;
$days = round($datediff / (60 * 60 * 24));
for($i=1;$i<=$days;$i++){
echo $date1 = date('d-m-Y', strtotime($date1 . ' +1 day'));echo ' <br> ';
}

You can try below using datediff() function
select id, fromdate, todate,datediff(ToDate,fromdate) as days
from tablename

Related

calculate years beetwen two dates laravel

i have mySQL database table field :
description
unit
start_date
end_date
for example :
start_date : 05-07-2019
end_date : 10-08-2021
how I calculate number of years?
Try this with carbon,
use Carbon\Carbon;
$startDate = Carbon::parse('05-07-2019');
$endDate = Carbon::parse('10-08-2021');
$diff = $startDate->diffInYears($endDate);
Hope this helps :)
Try
$datetime1 = new DateTime("05-07-2019");
$datetime2 = new DateTime("10-08-2021");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
Output will be
Difference: 2 years, 1 months, 5 days
Hope this helps :)
Try to use date_diff, in your example its will return 1.
$start_date = date_create("05-07-2019");
$end_date = date_create("10-08-2021");
$diff = date_diff($start_date, $end_date);
echo $diff->y;

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

Query database for Current Week Results [duplicate]

I have table temp with structure on sqlfiddle:
id(int 11 primary key)
name(varchar 100)
name2(varchar 100)
date(datetime)
I would like get record on this week, example if now 21.11.2013 i would like all rows on 18.11.2013 to 24.11.2013(on week)
Now I see next algorithm:
obtain weekday
calculate how many days ago was Monday
calculate the date Monday
calculate future date Sunday
make a request on date
Tell me please, is exist a shorter algorithm (preferably in the query MySQL)?
ADD Question is: Why this query select record on date 17.11.2013(Sunday) - 23.11.2013(Saturday) and how get records on date 18.11.2013(Monday) - 24.11.2013(Sunday) ?
query:
select * from temp
where yearweek(`date`) = yearweek(curdate())
Thanks!
Use YEARWEEK():
SELECT *
FROM your_table
WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)
Use YEARWEEK. If you use WEEKOFYEAR you will get records of previous years also.
SELECT id, name, date
FROM table
WHERE YEARWEEK(date)=YEARWEEK(NOW());
For selecting records of day, week and month use this way:
function my_func($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM your_table WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
You can do it by following method
SELECT DATE_FORMAT("2017-06-15", "%U");
Get number of week (From 00 to 53 )
Where (Sunday 1st day and Monday last day of week)
May be useful for you.
example:
SELECT DISTINCT DATE_FORMAT('dates', '%U') AS weekdays FROM table_name;
The short solution would be this:
SELECT * FROM my_table WHERE DATE_FORMAT("2021-08-19 15:40:33", "%U") = WEEK(CURDATE());

MySQL - DATE_ADD month interval by each month

I have written a function below to give me the number of jobs an employee has done in a particular 30 day period (each ID in the 'jobs column' of the table represents 1 job).
the function work fine if I only want to look back 4 week. the problem however is that I want the count to start at the beginning of each month. for example, if a person views the records on the 10th December 2013 I need the records to show all the work for December (but not the records for the preceding 30 days).
Below is my function:
$interval_1month = 'interval 4 WEEK';
function statsHowMuchWorkDoneByStaff ($staff_id, $timeInterval)
{
global $dbc;
$select = " SELECT
COUNT(job_id) AS totalnumberWork ";
$from = " FROM
staffwork
";
$where = " WHERE
staff_id = $staff_id
AND
FROM_UNIXTIME(entrytime) >= now() - $timeInterval";
$query = $select.$from. $where;
$result = mysqli_query ($dbc, $query)
or trigger_error("Query: $query\n<br />MySQL Error: " . mysqli_error($dbc));
if(mysqli_num_rows($result))
{
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
$result = safe_output($row['totalnumbernewcontacts']) ;
return $result ;
}
else
{
return false;
}
}
Any advise on how to proceed would be greatly appreciated.
UPDATE: here is my datatable:
CREATE TABLE staffwork(
staff_id MEDIUMINT UNSIGNED NOT NULL,
job_id MEDIUMINT UNSIGNED NOT NULL,
data_table VARCHAR (65) NOT NULL,
entrytime int(11) NOT NULL,
INDEX message (staff_id)
);
If I understand correctly and you want to calculate COUNT(job_id) for a specific month by supplying any date of that month as a parameter, then you can do it this way
SELECT COUNT(job_id) total
FROM staffwork
WHERE staff_id = 1
AND entrytime >= UNIX_TIMESTAMP(LAST_DAY('2013-12-10') + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND entrytime < UNIX_TIMESTAMP(LAST_DAY('2013-12-10') + INTERVAL 1 DAY)
Note: This query is index friendly because it doesn't convert entrytime to datetime but rather convert range values (which are constants for the query) to unix time. Make sure that you have indices on entrytime and staff_id to be able to take advantage of that.
Here is SQLFiddle demo
And while you're at it consider to learn and use prepared statements instead of interpolating query strings leaving your code vulnerable for sql injections.
That being said your php function might look like this
function statsWorkDoneByStaffMember($staff_id, $month) {
global $dbc;
$sql = "
SELECT COUNT(job_id) total
FROM staffwork
WHERE staff_id = ?
AND entrytime >= UNIX_TIMESTAMP(LAST_DAY(?) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND entrytime < UNIX_TIMESTAMP(LAST_DAY(?) + INTERVAL 1 DAY)
";
$stmt = $dbc->prepare($sql);
if (!$stmt) {
trigger_error('Prepare failed: ' . $dbc->error);
}
$stmt->bind_param('iss', $staff_id, $month, $month);
if(!$stmt->execute()) {
trigger_error('Execute failed: ' . $dbc->error);
}
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
return $result;
}
Sample usage:
$dbc = new mysqli('localhost', 'user', 'password', 'dbname');
$staff_id = 1;
//Get the number of job_id for the current month
$total = statsWorkDoneByStaffMember($staff_id, date('Y-m-d'));
//Get the number of job_id for a specific month
$total = statsWorkDoneByStaffMember($staff_id, '2013-07-01');

MySQL: How to select records for this week?

I have table temp with structure on sqlfiddle:
id(int 11 primary key)
name(varchar 100)
name2(varchar 100)
date(datetime)
I would like get record on this week, example if now 21.11.2013 i would like all rows on 18.11.2013 to 24.11.2013(on week)
Now I see next algorithm:
obtain weekday
calculate how many days ago was Monday
calculate the date Monday
calculate future date Sunday
make a request on date
Tell me please, is exist a shorter algorithm (preferably in the query MySQL)?
ADD Question is: Why this query select record on date 17.11.2013(Sunday) - 23.11.2013(Saturday) and how get records on date 18.11.2013(Monday) - 24.11.2013(Sunday) ?
query:
select * from temp
where yearweek(`date`) = yearweek(curdate())
Thanks!
Use YEARWEEK():
SELECT *
FROM your_table
WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)
Use YEARWEEK. If you use WEEKOFYEAR you will get records of previous years also.
SELECT id, name, date
FROM table
WHERE YEARWEEK(date)=YEARWEEK(NOW());
For selecting records of day, week and month use this way:
function my_func($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM your_table WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
You can do it by following method
SELECT DATE_FORMAT("2017-06-15", "%U");
Get number of week (From 00 to 53 )
Where (Sunday 1st day and Monday last day of week)
May be useful for you.
example:
SELECT DISTINCT DATE_FORMAT('dates', '%U') AS weekdays FROM table_name;
The short solution would be this:
SELECT * FROM my_table WHERE DATE_FORMAT("2021-08-19 15:40:33", "%U") = WEEK(CURDATE());