How to use current date in mysql query? - php

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

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

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

fetching record according current date

can any one explain how i would display my table record according date, like any user of my website can see their activity of current date only...
while($data=mysql_fetch_array($rs))
{
$data["create_date"]=date("M d,y" , $data[create_date]);
i am using this but it displaying previous date result also
here is my code, i am fetching result from different tables
$SQL="select * from $tab where 1 $con ORDER BY id desc $_REQUEST[sort_mode] $con_limit";
while($data=mysql_fetch_array($rs))
{
$data["create_date"]=date("M d,y" , $data[create_date]);
gri("users","WHERE id='$data[op_id]' ","",$op_name);
gri("patient", " where id ='$data[patient_id]' order by id desc","",$patient);
$data[first_name]=$patient[first_name];
$data[last_name]=$patient[last_name];
$data[age]=$patient[age];$data[sex]=$patient[sex];
$data[mob]=$patient[mob];
$data[op_name]=$op_name[name];
$t->set_var($data);
$t->set_var(array("chk_status_$data[id]_$data[status]"=>"selected",));
$t->parse("ABlockList","AccessBlockList",true);
}
You can also use MySQL for this.
Example
select * from table_name where create_date >= NOW();
OR
SELECT * FROM table_name WHERE DATE(create_date) = CURDATE();
OR
SELECT * FROM table_name WHERE DATE(create_date) = DATE(NOW())
DATE() returns the date without time and NOW() returns the current date & time (note we’ve used the DATE() function in this query to remove the time)

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.

Mysql query: retrieve current date query

In mysql database i have this column called:
Name: Date
Type: datetime
I have few values in that column:
2009-01-05 01:23:35
2009-03-08 11:58:11
2009-07-06 10:09:03
How do I retrieve current date? I am using php.
in php:
<?php $today = date('Y-m-d');?>
How to write a mysql query to retrieve all today date data?
Should i change the column type to "date", then insert values like "2009-07-06" only, no time values???
You don't need to use PHP, MySQL has a function to get the current date:
SELECT field FROM table WHERE DATE(column) = CURDATE()
Documentation: CURDATE, DATE.
If your column is only ever going to need the date part and never the time, you should change your column type to DATE. If you insist on doing it through PHP, it is the same thing, really:
$today = date('Y-m-d');
$query = mysql_query("
SELECT field FROM table WHERE DATE(column) = '$today'
");
For date time it is not usefull, instead I try this and working...
Today's Visitors!
sql > select user_id from users where last_visit like concat('%' , CURDATE() , '%');
// last_visit coloumn of type 'datetime'

Categories