Right now I have a MySQL table with one column called "date_time" that simply lists different DATETIME values (e.g. "2010-11-30 12:55:00"). Is it possible for me to construct a query that directly:
Selects DATETIME values where the month is the current month?
Selects DATETIME values where the days aren't passed days (e.g. tomorrow and until the end of the month?
An abstract query in my mind would look like:
$query = "SELECT * FROM meetings WHERE uid = " . $_SESSION['uid'] . "AND the DATETIME month is active month AND the DATETIME day is bigger than the active day"
Is this functionality possible in MySQL (did some searching but didn't find anything helpful), or will I have to use PHP functions later to filter this stuff out? Many thanks in advance.
MySQL has a ton of date formatting functions that would solve this for you:
Select by specific month...
SELECT ... WHERE MONTH(date_time) = MONTH(now());
Select by non-passed days:
SELECT ... WHERE DAY(date_time) > DAY(now());
Of course, these sorts of queries will pick out the same month/days in ANY records from ANY years. If you want to restrict to particular chunks of time, then you'll have to add more clauses.
Something like:
$query = "SELECT * FROM meetings WHERE uid = " . $_SESSION['uid'] . "WHERE EXTRACT(month from now()) = extract(month from date_time) AND EXTRACT(day from now()) < extract(day from date_time)
Related
I have s MySQL Query where I want to pull data from my database but base it on the current month information
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND DATE (lbs_date) = CURDATE()) ORDER BY lbs_date DESC LIMIT 0,50");
This string pulls out the information for the current day.
I have also tried the below string but get no results from it:
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND MONTH(lbs_date) = (MONTH(NOW()) AND YEAR(lbs_date) = YEAR(NOW())
My table date format is as follow 2016-08-02
Or using PHP variables as so:
<?php
$start = date('Y-m-01'); // FIRST DAY OF CURRENT MONTH
$end = date("Y-m-t", strtotime(date("Y-m-d"))); // LAST DAY OF CURRENT MONTH
$sql = "SELECT * FROM lbs_trace_etrack WHERE lbs_agent = '".$slfirstname."' AND (lbs_date BETWEEN '".$start."' AND '".$end."')";
?>
I have done the following and it works
FROM lbs_trace_etrack WHERE lbs_agent = '$slfirstname' AND MONTH(lbs_date) = MONTH(CURDATE()) AND YEAR(lbs_date) = YEAR(CURDATE()) ORDER BY lbs_date ASC, lbs_time ASC
Thanks to all and Tijo for guidance
Assuming lbs_agent is a DATE field type as mentioned in comments, you could do this (note I am just showing the pertinent date part of your WHERE clause):
WHERE lbs_agent >= DATE_FORMAT(NOW() ,'%Y-%m-01')
It is important that you do not use a function call on the left (field definition) side of the WHERE comparison, as you will then not be able to leverage any index on that field. Doing this would require a full table scan with MySQL performing the function on this field for every row in the table such that the comparison can be made.
Feel free to use MySQL functions for the comparison value, as those would be calculated just once when the query is being planned. You would then be able to use an index on the field for quickly filtering the rows in the table that meet the criteria. From a query execution standpoint, this is basically that same as if your query has this WHERE clause:
WHERE lbs_agent >= '2016-08-01'
This is as compared to the examples in your question which would be executed as:
WHERE DATE(lbs_date) = '2016-08-03'
and
WHERE MONTH(lbs_date) = 8 AND YEAR(lbs_date) = 2016
Both of these would require full table scan since the values derived from the field are not able to be determined until the row is scanned.
You could try to extract the month, such as EXTRACT(MONTH from NOW())
you can use following code if it timestamp
MONTH(CURDATE())
I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';
I have a database of customers and would like to run a query to display how many customers have an active account on a month by month basis.
I already have the following to count how many customers have an expiry date for each month, but can anybody suggest a way to then count those with an expirydate >= now for each month?
<?php
$query = "select count(cid) as num_rows from customers WHERE expirydate LIKE '%-12-%'";
$result = mysql_query($query);
$row = mysql_fetch_object( $result );
$total = $row->num_rows;
echo "December: " .$total;
?>
Simple
mysql_query( "select count(cid) as num_rows from customers WHERE expirydate >= curdate()" );
Try to avoid mysql_* functions due to they are depricated.Instead use mysqli_* functions or PDO statements
The following will tell you have many customers have an expirydate per month for records on or after today.
SELECT
MONTH(expirydate) month, COUNT(cid) as count
FROM
customers
WHERE
DATE(expirydate) >= CURDATE()
GROUP BY MONTH(expirydate)
Do note though that as this groups only by month, records spanning multiple years may be misleading (3 July 2013 and 7 Jul 2014 would both count as July, for example).
You should look into the date and time functions and group by/aggregate functions for more information.
This query show you how much customers has expirydate after now. Correct your date format in STR_TO_DATE function for your case. MySQL STR_TO_DATE
SELECT COUNT(*) as `num_rows`, MONTH(STR_TO_DATE(`expirydate`,'%Y-%m-%d')) as `month`
FROM `customers`
WHERE STR_TO_DATE(`expirydate`,'%Y-%m-%d') > NOW()
GROUP BY `month`
Also try to use timestamp field type in your tables instead of varchar or etc.
Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.
In my code, I am trying to find items in an activities table that are within the last day. This query is not returning any results, are there any problems with it? Is there a better query?
$curday = time() - (24*3600);
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > '$curday'";
There are two choices here, you can get and format the date through PHP or use SQL language to do it. I prefer to do it within the SQL, it also allows me to use the same query in a MySQL client.
This question is essentially the same thing: MySQL SELECT last few days?
This would be the new query:
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > DATE_ADD(CURDATE(), INTERVAL -1 DAY)";
you can try with unix function 'mktime' to get value of yesterday ..
as
$curday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
for reference
if your database will mysql only then you can extract yesterday in sql itself..
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY)
one more thing if timestamp is your column name don't put this column inside single quote ..
What you can use is DATE_SUB. This can be used as follows
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > date_sub(current_date, interval 1 day)
This way you don't need to work with current date in PHP
in Informix it would be (TODAY - 1) if the column is type DATE