Is there a way to write a MySQL query to get records by monthly for example:
Starting from the current month:
----- Jan -----
Record 1
Record 2
----- Feb -----
Record 1
Record 2
----- March-----
Record 1
Record 2
I have starting and ending timestamp and start_date, end_date(MM/DD/YYYY format) column in my db table.
solved by getting start date & end date of month
$month_start_time = strtotime(date('Y-m-01', $timestamp)." 00:00:00");
$month_end_time = strtotime(date('Y-m-t', $timestamp)." 23:59:59");
$sdate = date('d', $month_start_time);
$edate = date('d', $month_end_time);
$j=0;
for($k=$sdate; $k <= $edate; $k++){
$start_date = $k.date('/m/Y', $month_start_time);
$stimestamp = strtotime(date('Y/m', $month_start_time).'/'.$k." 00:00:00");
$end_date = strtotime(date('Y/m', $month_start_time).'/'.$k." 23:59:59");
//then pass in mysql query
}
Related
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);
I want to get the month name from a Do Until......Loop and display in a CheckedListBox.
I have two tables.
1. Month_Count
2. Fees_Ledger
My month name function...
Function mnthName(ByVal mnth As Integer)
Dim name As String = String.Empty
name = MonthName(mnth, False)
Return name
End Function
To get the Month Details
"SELECT FromMonth,ToMonth,MonthCount FROM Month_Count WHERE SemesterNumber='1'"
And to get the Paid Count
"SELECT COUNT(*) AS TotMonthPaidCount FROM Fees_Ledger WHERE SemYear='1' AND FeeId='1'"
So...
' Got the values from queries
FromMonth = 7 '(July)
ToMonth = 6 '(June)
MonthCount = 12 '(Loop will rotate 12 times)
TotMonthPaidCount = 1 '(FeeId 1 paid one time)
'Declaring an integer variable
Dim StartM As Integer = 1
FromMonth = FromMonth + TotMonthPaidCount
' For the first month
CheckedListBoxMonth.Items.Clear()
CheckedListBoxMonth.Items.Add(mnthName(FromMonth))
' Now the loop to achieve the goal
Do Until StartM = (MonthCount - TotMonthPaidCount)
If FromMonth >= 12 Then
FromMonth = 1
CheckedListBoxMonth.Items.Add(mnthName(FromMonth))
Else
FromMonth += 1
CheckedListBoxMonth.Items.Add(mnthName(FromMonth))
End If
StartM += 1
Loop
This Subroutine results exactly what I want.
But the problem occurs when the StartMonth = FromMonth (6) + TotMonthPaidCount (7) value >12. As 13 or 14 or 15 has no Month Name, it is showing error.
Argument 'Month' is not a valid value.
I want it like below.
What should I do ?
I have a sql booking question. The table has idstylist, bdate, stime and etime.
Basically the stylist can only do one job at a time. So when placing a booking I need to check that that stylist is not already busy on another booking. Here is my clash method;
public function checkClash($bdate, $stime,$stylist){
$query = sprintf("SELECT id FROM table WHERE (date=%s AND idstylist=%s) AND (%s BETWEEN stime AND etime)",
$this->db->GetSQLValueString($bdate, "date"),
$this->db->GetSQLValueString($stylist, "int"),
$this->db->GetSQLValueString($stime, "text"));
$result = $this->db->query($query);
if($result && $this->db->num_rows($result) > 0){
return true;
}
return false;
}
As far as I understand my query is selecting all bookings from (date) where idstylist is this and the start time is >= $stime but <=$stime.
So for example I have a row in the database that looks like this;
id | date | idstylist | stime | etime
1 | 2014-12-05 | 68 | 07:00:00 | 07:30:00
Now Im trying to place a booking for the same stylist at 07:10:00 on the same date which should fail but the system is allowing me to make this booking. I cant see whats wrong with my query.
//next check for clashes in the booking table
$clash = $bookings->checkClash($_POST['bdate'],$_POST['stime'], $_POST['stylist']);
if($clash==true){
$errors[] = "Booking clashes. Please try again";
}
This is turning into a debugging session.
From your SQL: (stime>=%s AND etime<=%s)
Replace with values: ('7:00' >= '7:10' AND '7:30' <= '7:10')
I gues you want: (%s BETWEEN stime and etime)
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');
I'm getting a weird return when executing this query :
SELECT * FROM rrp
WHERE end > "2012-12-31"
nothing is returned, although I have one row on this table which "end" column is greater than "2012-12-31":
rrp
id_r | id__b | start | end | quantity
27 29 2012-01-01 2012-05-05 1
31 29 2012-11-01 2013-01-01 1
EDIT : startand endare date fields
EDIT : I used wrong database for my tests => wrong result
the issue was coming from Zend_Date when adding a day to a date:
$start = "2012-12-31";
$nStart = new Zend_Date($start, "YYYY-MM-dd");
$end = new Zend_Date($nStart);
$end->addDay(1);
When i echoed $end : echo $end->get("YYYY-MM-dd");
it outputs 2013-12-31
Most likely an issue with how the dates are formatted
This should help
http://dev.mysql.com/doc/refman/5.0/en/using-date.html
If end is a DATE column, it should work as expected:
SELECT
STR_TO_DATE('2013-01-01', '%Y-%m-%d') < "2012-12-31",
STR_TO_DATE('2012-05-05', '%Y-%m-%d') < "2012-12-31"
... returns 0, 1 in my box.
The only possible flaw I can think of is that your system's default date format is not %Y-%m-%d:
SELECT ##DATE_FORMAT
In that case, you need to specify a format every time:
SELECT *
FROM rrp
WHERE end > STR_TO_DATE('2012-12-31', '%Y-%m-%d')