MySQL order by time stored as HH:MM:SS - php

I have a varchar typed field which stores strings in this format HH:MM:SS i.e. 01:25:59 (and sometimes without HH part e.g. 25:59).
I want to have a descending order of results based on this time and for that I came with [str_to_date()][1] function and currently I'm using str_to_date($field_value,'%l:%i:%s') DESC to achieve this kind of sorting.
The odd thing is by using this format %l:%i:%s all posts having this field in MM:SS format are ordered correctly but those in HH:MM:SS aren't.
1-So if I have these values:
11:35
15:20
48:00
01:57:47
01:20:26
2-They are sorted as:
48:00
01:20:26
15:20
11:35
01:57:47
3-Which is wrong and should be:
01:57:47
01:20:26
48:00
15:20
11:35
As you see in (2) only times in format of HH:MM:SS are not placed correctly (DESC)
How can I have the right sorting?

What about this?
SELECT * FROM tbl
ORDER BY TIME_TO_SEC(IF(LENGTH(str_time)<6,CONCAT("00:",str_time),str_time)) DESC
fiddle demo: http://sqlfiddle.com/#!9/4b5da/3

This is your query:
SELECT IF(LENGTH( columnName ) >5, STR_TO_DATE(columnName, '%h:%i:%s'), STR_TO_DATE(columnName, '%i:%s')) as modDate
FROM `tableName` WHERE 1 order by modDate desc
SQL Fiddle: http://sqlfiddle.com/#!9/b6a52/1

wanna do something at application side ??? bit lengthy, but it works.
$tim_arr = array ('11:35', '15:20', '48:00', '01:57:47', '01:20:26');
$new_arr = array();
foreach ($tim_arr AS $tim){
$tim_chk = $key = '' ; $ntim_arr =array();
$tim_chk = substr_count($tim, ":");
$ntim_arr = explode(':',$tim);
if($tim_chk == 2){
$ntim = ( (int)$ntim_arr[0]*60 + (int)$ntim_arr[1] ).':'.$ntim_arr[2];
$key = ( (int)$ntim_arr[0]*60 + (int)$ntim_arr[1] );
}
else{
$ntim = $tim;
$key = $ntim_arr[0];
}
$new_arr[$key] = $ntim ;
}
krsort($new_arr);
foreach ($new_arr AS $tim)
{
$ntim_arr = explode(':',$tim);
if((int)$ntim_arr[0] >= 60){
echo str_pad(floor($ntim_arr[0] /60),2,"0",STR_PAD_LEFT).":".
str_pad($ntim_arr[0] %60,2,"0",STR_PAD_LEFT).":".$ntim_arr[1]."<br/>";
}
else{
echo $tim."<br/>";
}
}

Related

Sorting multiple date formats

In database I've got column date_of_premiere (type: INT). Passing the validation that column can store three "types" of values:
YYYY (e.g. 2016, when there's no info about specific month and day)
YYYYMM (e.g. 201511, when there's no info about specific day)
YYYYMMDD (e.g. 20151101)
I've got problem with sorting, becouse when I'm try to sort that column...
$query = $this->db->query(" SELECT * from table order by `date_of_premiere ");
... records with format YYYY will always first.
When I fetch the data, I can do some kind of workaround...
$dates =[];
while($row = $query->fetch_assoc())
{
if(strlen($row['date_of_premiere']) == 4)
{
$dates[] .= intval($row['date_of_premiere'] .'0000');
} else if (strlen($row['date_of_premiere']) == 6)
{
$dates[] .= intval($row['date_of_premiere'] .'00');
} else
{
$dates[] .= intval($row['date_of_premiere']);
}
}
...then I can do asort($dates)...
// input values: 2015, 2016, 201511, 20151101
// example output with correct sorting:
Array
(
[1] => 20150000
[0] => 20151100
[3] => 20151101
[2] => 20160000
)
... but I'm curious is there way to sort date_of_premiere using mysqli query only.
You can order by the dates' column casted as CHAR:
... ORDER BY CAST(date_of_premier AS CHAR(32))

sum of 2D array in php

I have a situation where I need to generate total sales of each month.
I can show total sales of 12 month in a certain area but I need to show total sales of any month of a certain area. i.e: total sales of June at Head Office area.
my sample code is as follows:
while($area = mysql_fetch_array($exe_area))
{
for ($m=1; $m<=12; $m++) {
.........
echo $total_sold;
$sales_of_year+= $total_sold;
} // end of month listing....
echo $sales_of_year;
} // end of area listing...
U may try this !!!
$tmp = explode( '|', $str );
$data = array();
foreach ( $tmp as $k => $v )
{
$data[] = explode( ',', $v );
}
It looks like your data is being retrieved from the database, in which case you can extract the total sum with your query:
SELECT SUM(column_name) FROM table_name;
Or, to analyse a particular month, depending on your database schema, you can do:
SELECT SUM(column_name) FROM table_name WHERE month = 'June';

Replacing redundant dates in DB query with symbol (MySQL/PHP)

I have a database query that displays a list of historic events in chronological order, like this:
(URL = MySite/Calendar/January_1)<br>
On this day in history...<br>
1968 - A volcano erupted.<br>
1968 - A country was invaded.<br>
1968 - Someone had a hit song.<br>
1970 - A famous person was born.
I'd like to know if there's a way to display a year just once, so the display looks like this:
1968 - A volcano erupted.<br>
• A country was invaded.<br>
• Someone had a hit song.<br>
1970 - A famous person was born.
Let's start with a database table (calendar_px) that lists the dates of various historic political events. The table has five fields -
1) N (a simple numerical key)
2) URL (values - such as May_1 - match page URL's)
3) Year (e.g. 1970, but the field type is INT, not Year, which only goes back to 1901)
4) Brief (some brief content)
5) Date (field type will be either date or datetime; I'm not actually using this field at the moment)
Here's what my code looks like (where $MyURL equals the page URL; e.g. January_1):
$stm = $pdo->prepare("SELECT Cal2.N, Cal2.URL, Cal2.Date, Cal2.Year, Cal2.Brief
FROM calendar_px Cal2
WHERE Cal2.URL = :MyURL
ORDER BY Cal2.Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
while ($row = $stm->fetch())
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}
Then, I display a list of historic events like this...
echo join( $Brief, '<br>' );
I don't think it really changes anything, but I should mention that I have a similar set up on several websites; everything is the same except for the table names:
calendar_gw, calendar_gz, calendar_gs, calendar_px, calendar_sl
Accordingly, I've joined all five tables together with a UNION command. Here's a portion of the query:
$stm = $pdo->prepare("SELECT CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief
FROM calendar_gw CGW
WHERE CGW.URL = :MyURL
UNION ALL
SELECT CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief
FROM calendar_gz CGZ
WHERE CGZ.URL = :MyURL
UNION ALL
SELECT CSL.N, CSL.URL, CSL.Date, CSL.Year, CSL.Brief
FROM calendar_sl CSL
WHERE CSL.URL = :MyURL
ORDER BY Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
Anyway, my goal is the same; to replace redundant dates (years) with some sort of "dingbat" or symbol.
$prevYear = null;
while ($row = $stm->fetch())
{
$Year = $row['Year'];
if ($Year == $prevYear) {
$YearStr = '• ';
} else {
$YearStr = $Year . ' $#8211; ';
$prevYear = $Year;
}
$Brief[] = $YearStr.$row['Brief'];
}
P.S. You don't need to concatenate '' at each end of the string.
Looks like you need to group resultset before outputting:
$events = array();
while($row = $stm->fetch()){
$year = $row['Year']; // current year
if(!isset($events[$year]){ // if no such group
$events[$year] = array(); // create group
}
$events[$year][] = $row['Brief']; // add data to year group
}
// Output:
foreach($events as $year => $event){
echo $year, ':<br>'; // show year;
foreach($event as $data){
echo $data, '<br>'; // show row;
}
}
Also, you may change output to your model, easily:
foreach($events as $year => $event){
echo $year, ' • ', implode('<br>• ', $event);
}

multiple dates datetime

I am trying to display a table with PHP MYSQL where the FIELD is the DATE and rows are TIME from a MySQL database with unknown/infinite records, one with different TIMES for the same DATE, by querying it for the DateTime.
My mysql date stores the dateTime in the same column, but I am splitting this and trying to display them seperately. BUT I cannot seem to display the date only once and the time multiple times, it is just both.
$sql_result = mysqli_query($connection, "SELECT DATE(date_time) AS date_part, TIME(date_time) AS time_part FROM $table WHERE date_time LIKE '$date_input%'");
if (mysqli_num_rows($sql_result) == 0)
{
echo "<p>No bookings exist.</p>";
}
else {
echo "<h3>Results for booked " . $table . " Appointments:</h3>";
echo "<h3>" . $formattedDate ."</h3>";
while ($row = mysqli_fetch_array($sql_result))
{
echo $row['date_part'];
$array_time = array($row['time_part']);
foreach ($array_time as $time_output)
{
echo $time_output;
}
}
}
My output is like this:
2013-12-0809:00:002013-12-0810:00:002013-12-0811:00:002013-12-0812:00:002013-12-0814:00:002013-12-0815:00:002013-12-0816:00:002013-12-0817:00:002013-12-0909:00:002013-12-0809:00:00
But I would like it like this:
2013-12-08 09:00:0010:00:0011:00:0012:00:0014:00:0015:00:0016:00:0017:00:0009:00:000
2013-12-09 9:00:00
Hrrmm. Theres a bit of logic problem here:
while ($row = mysqli_fetch_array($sql_result))
{
echo $row['date_part'];
$array_time = array($row['time_part']); // HERE
foreach ($array_time as $time_output)
{
echo $row['time_part'];
}
}
$array_time will always have only one value, since $row['time_part'] only refers to ONE row (each iteration of while ($row = mysqli_fetch_array($sql_result)) reassigns a single row to $row)
try doing this first pass to define a workable array
while ($row = mysqli_fetch_array($sql_result))
{
$array[$row['date_part']][$row['time_part']] = 1; // the value assigned doesn't matter, all we wish is a definite hierarchy
}
this will give you an array like:
['2013-12-08']['9:08'] = 1
['12:30'] = 1
[23:17] = 1
['2013-12-09']['10:00'] = 1
[14:20] = 1
THEN! you can foreach through your result
foreach ($array as $date_part => $array_time)
{
echo $date_part . ' ';
foreach ($array_time as $time_part => $i) // again our $i is not used
{
echo $time_part;
}
echo '<br>'; // here it breaks line after all times for the date has been echoed
}
You need to GROUP in your query:
SELECT DATE(date_time) AS date_part, TIME(date_time) AS time_part
FROM $table
WHERE date_time LIKE '$date_input%'
GROUP BY date_part
I think I understand what you're trying to say, however, MySQL won't create a multidimensional array. You should try something like this:
$dates = array();
while ($row = mysqli_fetch_array($sql_result)) {
$dates[$row['date_part']][] = $row['time_part']
}
Then you could have something like this:
foreach ($dates as $key => $value) {
echo $key.'<br />';
foreach ($value as $time) {
echo $time.' - ';
}
echo '<br />';
}
which should look something like:
2013-09-01
09:00 - 09:30 - 10:20 - 11:00
2013-09-02
10:12 - 11:00 - 12:24 //etc
Hope this helps!
Two comments. First, it seems like you need an order by time so as to order your records.
SELECT DATE(date_time) AS `date_part`, TIME(date_time) AS `time_part`
FROM $table
WHERE date_time LIKE '$date_input%'
ORDER BY date_time ASC
Second, if I read your question correctly, it seems like you want to output your data into two columns, one with date and the other with all times for that date. You might consider using GROUP_CONCAT() to do this in SQL, making your output easy.
SELECT DATE(date_time) AS `date_part`, GROUP_CONCAT(TIME(date_time)) AS `times`
FROM $table
WHERE date_time LIKE '$date_input%'
GROUP BY `date_part`
ORDER BY date_time ASC
This would give output like
date_part times
2013-12-08 11:22:33,11:33:44,12:44:55
2013-12-09 12:00:00
With this approach, there would be no need to build a multi-dimensional array in PHP, as the data would come out of the database just the way you need it. That also means that you don't need to load the entire result set into memory in order to work with it (as you would have to do if creating multi-dimensional array).

How to break up reports by month with php and mysql?

I'm trying to do something relatively simple here. Basically I have a table with a bunch of rows in it marked with a timestamp (format: 2009-05-30 00:14:57).
What I'm wanting to is do is a query which pulls out all of the rows, and splits them by the month so I'm left with a final result like:
February
rowID name order date
rowID name order date
rowID name order date
January
rowID name order date
rowID name order date
rowID name order date
etc.
I have a few vague ideas how to do this - they just seem long winded.
One of the ways would be to do a query for each month. I'd derive what the current month is in PHP then construct a for() which goes back a certain number of months.
like:
$currentmonth = 8;
$last6months = $currentmonth - 6;
for($i = $currentmonth; $i == $last6months; $i--) {
$sql = 'SELECT * FROM reports WHERE MONTH(reports.when) = $currentmonth ';
$res = mysql_query($sql);
// something would go here to convert the month numeral into a month name $currentmonthname
echo $currentmonthname;
while($row = mysql_fetch_array($res)) {
// print out the rows for this month here
}
}
Is there a better way to do this?
It's better to fetch all data once,ordered by month..
Then while fetching with php you can store your current month in a variable (for example $curMonth) and if there is a change in the month, you echo "New Month"...
Executing a query is slow, it's better to minimize your "conversations" with the db..
Don't forget that you have to deal with years aswell. If you have two records, one for January '09 and one for January '08, your results may be skewed.
Best to follow Svetlozar's advice and fetch all data at once. Once you have it in memory, use PHP to segment it into something usefull:
$monthData = array();
$queryResult = mysql_query("
SELECT
*,
DATE_FORMAT('%m-%Y', when) AS monthID
FROM
reports
WHERE
YEAR(when) = 2009 AND
MONTH(when) BETWEEN 5 and 11
");
while ($row = mysql_fetch_assoc($queryResult))
{
if (!isset($monthData[$row['monthID']]))
$monthData[$row['monthID']] = array();
$monthData[$row['monthID']][] = $row;
}
mysql_free_result($queryResult);
foreach($monthData as $monthID => $rows)
{
echo '<h2>Data for ', $monthID, '</h2>';
echo '<ul>';
foreach($rows as $row)
{
echo '<li>', $row['someColumn'], '</li>';
}
echo '</ul>';
}
You could change your SQL query to get your entire report. This is much more efficient than querying the database in a loop.
select
monthname(reports.when) as currentmonth,
other,
fields,
go,
here
from reports
order by
reports.when asc
You could then use this loop to created a nested report:
var $currentMonth = '';
while($row = mysql_fetch_array($res)) {
if($currentMonth !== $row['currentMonth']) {
$currentMonth = $row['currentMonth']);
echo('Month: ' . $currentMonth);
}
//Display report detail for month here
}
*Note: Untested, but you get the general gist of it I'm sure.
This is the SQL script:
SELECT*, DATE_FORMAT(fieldname,'%Y-%m') AS report FROM bukukecil_soval WHERE MONTH(fieldname) = 11 AND YEAR(fieldname)=2011
I hope you know where you should put this code :D

Categories