Format date from mysql query with multiple tables - php

I have an sql query that I use to display the news section of my website.
I would really love for the dates to be presented as "2nd January, 2012" however as I am selecting all fields from 5 tables I don't know where to put my formatting requirements (I am not selecting individual fields).
My query is below:
$query_newsheadlines = "
SELECT *
FROM
NewsArticles,
NewsArticleCategories,
NewsArticlePhotos,
NewsCategories,
NewsPhotos
WHERE
NewsArticles.id = NewsArticleCategories.newsArticleID
AND NewsArticles.id = NewsArticlePhotos.newsArticleID
AND NewsArticlePhotos.newsPhotoID = NewsPhotos.id
AND NewsArticleCategories.newsCategoryID = NewsCategories.id
AND NewsCategories.SectionID = 201
ORDER BY NewsArticles.publishDate DESC";
Any ideas would be appreciated :)
update the column my date is located in is NewsArticles.publishDate

you need to specify what column do you want to be formatted (just don't be lazy on specifying the column). Use DATE_FORMAT
SELECT DATE_FORMAT(CURDATE(),'%D %M, %Y')
SQLFiddle Demo
Other Source(s)
DATE_FORMAT()

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

PDO : get a list of unique similar part of value

I'm fetching data with PDO from a table containing 2 fields : comment and date.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo $comment;
echo $date;
}
Which displays a list of all comments.
Now I'm trying to group these comments by month, the main goal is to create some filter menu with a GET value so that only the current month comments are displayed :
<ul>
<li>October 2014</li>
<li>November 2014</li>
<li>December 2014</li>
</ul>
I think I should be fine with the LIKE operator for displaying the results, but what about the menu links generation ?
Main issue : $date is in d/m/Y format, so I have to process before using it :
$created = $date;
$month = $created->format('mY');
Also I can't really know in advance which months are going to be registered in the table, so it have to be "dynamic".
So how do I get a list of every month appearing in the table ? Without redundancy of course. Like
1014
1114
1214
even if there is numerous comments created on October for instance.
You can use MySQL's STR_TO_DATE and DATE_FORMAT functions to return the date in the format you need. For example:
SELECT `comment`, DATE_FORMAT(STR_TO_DATE(`date`, "%d/%m/%Y"), "%m%y") as `date2` FROM `data`
If you need to query all the unique month/year combinations, use DISTINCT:
SELECT DISTINCT DATE_FORMAT(STR_TO_DATE(`date`, "%d/%m/%Y"), "%m%y") as `date2` FROM `data`
Here's a SQL fiddle showing the distinct select.

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.

How to select certain data from a same field

Now currently facing a problem that is..
My table name is schedule
One of the data field is 'Depart'
the record is
row 1 = 19-08-2012 08:00:00AM,
row 2 = 19-08-2012 12:00:00PM,
row 3 = 20-08-2012 07:00:00PM,
I just want to display the date only and it is distinct
mysql_query(Select distinct depart from schedule);
This display date and the time.
Any one here know how to display the date only?
Example
SQL (recommended)
SELECT DISTINCT DATE( depart )
FROM `tbl`
PHP
$d = "19-08-2012 08:00:00AM";
echo date("d-m-Y",strtotime($d));
You can use DATE_FORMAT() function in the Mysql, as follows :
select DATE_FORMAT(distinct(Depart),'%m-%d-%Y') from schedule
Yes, use DATE:
SELECT DISTINCT DATE(`depart`) FROM `schedule`

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