MySql Query for Current Date - php

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())

Related

Display records in current month, using php and a mysql db

Im trying to display records in the current month from a column thats a timestamp.
This is my code
$query = "SELECT
donationid
FROM
donation
ORDER BY
donationid
WHERE
MONTH(donatedon) = MONTH(CURRENT_DATE())";
$query_run = mysqli_query($conn, $query);
$row = mysqli_num_rows($query_run);
echo '<h1>'.$row.'</h1>';
You're not checking the year, so you'll return records in the current month in any year, not just the current month.
Testing a function of a column prevents an index from being used to optimize the query. It's better to use a relational comparison if possible. You can simply create a formatted date for the beginning of the current month.
You also have ORDER BY in the wrong place, it has to be after the WHERE clause.
SELECT donationid
FROM donation
WHERE donatedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
ORDER BY donationid

PHP Date and Time, getting the 1st, 2nd, 3rd, and 4th week in a month

I'm using ChartJS to build a few graphs for ticketing applications.
What I'm trying to do is query the MySQL database for # of tickets created for the 1st, 2nd, 4rd, and 4th week of the current month.
$month_num_tickets = array();
for ($x=0;$x<=30;$x=$x+6) {
$from = date("Y-m-d 00:00:00",strtotime('first day of this month +'.$x.' days', time()));
$to = date("Y-m-d 23:59:59",strtotime($from, time()));
$get = mysql_query("SELECT id FROM tickets WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND assigned_tech_uid='$uid'") or die(mysql_error());
$month_num_tickets[] = mysql_num_rows($get);
}
Not sure how to setup the loop...
You can get a nice tidy count in a single query like this:
SELECT
CEIL(DAYOFMONTH(FROM_UNIXTIME(date_created)) / 7) AS week_of_month,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_of_month`
ORDER BY `week_of_month` ASC
Note if you used native datetime or timestamp fileds, you could get rid of all of those FROM_UNIXTIME conversions. This is based on a "week" being the first 7 days of the month, not based on specific days of the week. If you wanted it based on fixed weeks (in terms of sunday through saturday or such) you could just use WEEK() function in the SELECT instead.
That might look like this:
SELECT
WEEK(FROM_UNIXTIME(date_created), 0) AS week_number,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_number`
ORDER BY `week_number` ASC
Here week_number would be a value between 0-53 and would not necessarily have any meaning for display other than as a means for aggregation. I am using mode 0 for WEEK() functoin as this specifies Sun-Sat week. You can look at the definitions here and determine what mode suits you the best: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
None of these queries are optimized because you won't be able to use an index on date_created . If you do get around to changing that column type to a datetime or timestamp, you would also perhaps want to change you WHERE condition to the slightly less easy to read, but more index friendly version like this:
WHERE date_created BETWEEN '2014-12-01 00:00:00' AND '2014-12-31 23:59:29'
I think this should work for you
SELECT YEARWEEK(date_created), MONTH(date_created), COUNT(*) FROM tickets
WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND
assigned_tech_uid='$uid'
GROUP BY YEARWEEK(date_created), MONTH(date_created)

How to use current date in mysql query?

I have a database that contains a column with type - Date. I also have a query with the date inputted as static which works fine but I would like to use todays date in the query. any recommendations?
Query :
$q = 'SELECT count(ID) as count FROM ORDER WHERE
ASSIGN_TO ='.$db->qstr($person).' AND OPEN_DATE ='.$db->qstr('2014-05-14');
This currently displays count of items after 2014-05-14
You could use the NOW() function that returns the current date. To avoid skewed answered by hours/minutes/seconds, you can use date to extract the date part:
$q = 'SELECT count(ID) as count FROM ORDER WHERE
ASSIGN_TO ='.$db->qstr($person).' AND DATE(OPEN_DATE) = DATE(NOW())';

MySQL & PHP: summing up data from a table

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.

SQL Items within the Last Day

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

Categories