getting current (system) day using an SQL query in PHP - 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';
?>

Related

Oracle Where First and Last Day returned ORA-00904: "NOV": invalid identifier

I'm pretty new in Oracle and I want count data from first day and last day of this month (dynamically).
My PHP code look like this :
$date = Date('d-M-y');
// Query
$query = "Select COUNT(*) FROM myTable WHERE CREATED
BETWEEN FIRST_DAY(TRUNC(TO_DATE(".$date."), 'MON')) AND
LAST_DAY(TRUNC(TO_DATE(".$date."), 'MON'))";
But I always get the error
ORA-00904: "NOV": invalid identifier
Which NOV is the correct month -right?
If you leave it to oracle you could use
$query = "Select COUNT(*) FROM myTable WHERE TRUNC(SYSDATE,'MON') = TRUNC(CREATED,'MON')";
If you have an index on CREATED it could be faster to use
$query = "Select COUNT(*) FROM myTable WHERE CREATED >= TRUNC(SYSDATE,'MON') AND CREATED < TRUNC(ADD_MONTH(SYSDATE,1),'MON')
thanks for trying to answer, but i got this to solve my problem :
for get first day in month i used :
"TRUNC(TO_DATE('".$date."', 'DD-MM-YY'), 'MM')"
for last day, use :
"LAST_DAY(TO_DATE('".$date."', 'DD-MM-YY'))"

Comparing date() in sql query

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

How to fetch record by month in MySQL?

I have stored Date in database in dd-mm-yy format, for example 03-10-2013,
How to search record by month? Month in digit (01 to 12);
I am using currently
$query = "SELECT * FROM data WHERE date LIKE %$month%";
but this not working properly.
I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.
Based on that there are few ways to do this.
Leave the database as it is and convert values on the fly.
SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;
Change the type of the column to a "date" type column
SELECT * FROM data WHERE Month(realdatecolumn) = 5;
Change the type of the column to a "date" type column, store a separate column for the month.
UPDATE data set monthcolumn = Month(realdatetimecolumn)
then
SELECT * FROM data WHERE monthcolumn = 5;
Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data
Fix the date format in your database structure first, change it to: yyyy-mm-dd
Then change your query statement to:
$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';
This will select the month as '5' or '11' or '12' which will give duplicates for differing years.
If you need the month with year (to avoid duplicate years):
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);
This will return: '2015-01' or '2014-12'
To get date as '01' or '04' or '12':
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);
Try this...
You could use MySQL MONTH() function
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0
4 is april
SELECT * FROM tbl WHERE MONTH( date ) ='4'
You can do like it... as it is not in date format(YYYY-MM-DD)
$q="SELECT * FROM data WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";

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.

Categories