Comparing date() in sql query - php

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';

Related

MySql Query for Current Date

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

Using Date functions to pull records from database

I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?
Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();
You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)
It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.

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

getting current (system) day using an SQL query in PHP

I have this MySQl database that has a table which contains a column that contains days of the week like "Mon", "Tue" etc.
How do I get query the database and match this column content with the current (system) day?
like say
select .... where tablename.columnname = systemday
thanks.
Try using date_format(now(), "%a") as your condition value.
Read more here: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Haven't you tried searching ?
Anyways i hope you want something like this,
$cur_day= date('D');
select .... where tablename.columnname = $cur_day;
WHERE tablename.columnname = substr(dayname(now()),1,3)
or
WHERE tablename.columnname = date_format(now(),'%a')
Note, however, that it may be affected by locale settings.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.
Example:
SELECT * FROM mytable WHERE dayOfTheWeek=WEEKDAY(NOW())
Also, you can do this using PHP`s strftime and date functions:
$query1 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.date('N').'"');
$query2 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.strftime('%u').'"');
But, I think, it is better to generate this in PHP-only way.
<?php
$day=date('D');
$sql='select * from the_table where the_table.'.$day.'=systemday';
?>

Categories