Group By and displaying entries under date - php

Here's my data:
id date
1 2009-01-01 10:15:23
2 2009-01-01 13:21:29
3 2009-01-02 01:03:13
4 2009-01-03 12:20:19
5 2009-01-03 13:01:06
What I'd like to do is group by each date and then list the id numbers below each date. Should I be getting the distinct date values and then cycling through them to get the entries that fall on the date? is this efficient?
so my output would look like:
2009-01-01
1
2
2009-01-02
3
2009-01-03
4
5

$query = "SELECT DATE(date) as mydate, id FROM your_data_table ORDER BY mydate, id";
$result = $pdo->query($query);
$oldDate = false;
while ( list($date, $id) = $result->fetch(PDO::FETCH_NUM) ) {
if ( $oldDate != $date ) {
echo "$date\n$id\n";
$oldDate = $date;
} else {
echo "$id\n";
}
}
Instead of doing it in several queries, you just fetch all the data at once. If you only need some dates then you just put a WHERE clause before the ORDER BY.

Your stored dates have time information (the type of the column is DATETIME or TIMESTAMP), in order to do a group by, you need to extract only the date part your timespan, you can use the DATE() function.

Related

php fetch date column from database

SELECT c.enddate FROM cohort c ORDER BY c.enddate DESC LIMIT 1
I have a sql query above, it works in database, the result select a date like: '2018-07-18'
I try to use while loop with mysqli_fetch_row in php to fetch this date, but the result will only fetch:
2018
How can I get the whole date?
if ($runquery = $conn->query($result_validation))
{
//get the enddate from the last cohort
while ($row = mysqli_fetch_row($runquery))
{
$lastDate = $row[0];
}
}
$row[0] only display first number: 2018.
Adding DATE() function in the column will convert it to a valid date format like for the example below!
SELECT DATE(c.enddate) FROM cohort c ORDER BY DATE(c.enddate) DESC LIMIT 1
Try SELECT DATE(c.enddate) FROM cohort c ORDER BY c.enddate DESC LIMIT 1,
Try this one
SELECT DATE_FORMAT(c.enddate,"%Y-%m-%d") FROM cohort c ORDER BY c.enddate DESC LIMIT 1
The DATE_FORMAT() function formats a date as specified by a format mask.

Calculating data from one DB table with range of dates

I have sql function:
$sql = "SELECT date(datum_ura) as datetime,
COUNT(CASE rezultat_status_fk WHEN 5 THEN rezultat_status_fk END) AS half_lost, AVG(kvota) as average, SUM(vlozek) as vlozek,
SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota WHEN 2 THEN vlozek WHEN 3 THEN 0 END) AS case_profit,
SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota-vlozek WHEN 2 THEN 0 WHEN 3 THEN -vlozek END) AS profit
FROM bs_analiza
WHERE users_fk=$user_id"." group by date(datum_ura)";
The function is getting data from one table and calculates it and show results by dates. I'm trying to do a function which can sum current date result with the day before result....and so on.
I'm thinking of something like:
foreach ($items as $key => $value) {
$date = $value->datetime;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$prev_date = strtotime($prev_date);
$i = $key-1;
$profit_before = $items[$i]->$prev_date;
But I'm still getting the same results.
You can achieve this with selects from your intermediate result, I suggest you either create a view or use WITH.
SELECT
datetime,
(SELECT SUM(vlozek) FROM ... WHERE datetime >= t.datetime) vlozek_cumsum,
(SELECT SUM(case_profit) FROM ... WHERE datetime >= t.datetime) case_profit_cumsum,
(SELECT SUM(profit) FROM ... WHERE datetime >= t.datetime) profit_cumsum
FROM
... t
ORDER BY
datetime DESC
... is your intermediate result.
Edit (to clarify): You get your intermediate result by a select statement. So you can either
Create a view and replace ... by the name of the view or
CREATE OR REPLACE VIEW <view_name> AS <select_stmt>
Use WITH and replace all ... in the query above by the alias name.
WITH <alias_name> AS ( <select_stmt> )
SELECT
...

select records from sql database order by date DESC, but I want show records in table in date ASC

I have 7 records in a table but I want select only last 5 records sorting by date DESC. And I want to show these records in my table sorting by date ASC.
My Code:
$select_record = mysqli_query($con, "select * from table order by date DESC limit 5");
while($row=mysqli_fetch_array($select_record)){
$date = $row['date'];
echo "<tr><td>$date<br></td></tr>";
Records in My Table like this
Date
2014-05-15
2014-04-15
2014-06-15
2014-02-15
2014-07-15
2014-01-15
2014-03-15
My code give me result like this
Date
2014-07-15
2014-06-15
2014-05-15
2014-04-15
2014-03-15
But I want result like this
Date
2014-03-15
2014-04-15
2014-05-15
2014-06-15
2014-07-15
Do second SELECT on top of first one:
SELECT t.* FROM
(SELECT * FROM `table` ORDER BY `date` DESC LIMIT 5) t
ORDER BY t.`date` ASC
short version:
(SELECT * FROM `table` ORDER BY `date` DESC LIMIT 5) ORDER BY `date` ASC
Edit your while loop:
Instead of doing this:
while($row=mysqli_fetch_array($select_record)){
$date = $row['date'];
echo "<tr><td>$date<br></td></tr>";
}
Try doing this:
create an array that can store your date values retrieved from query
while($row=mysqli_fetch_array($select_record)){
$date = $row['date'];
Add $date to the array you created
}
Iterate the array from the END to START and print dates .
{
echo "<tr><td>$date<br></td></tr>";
}
Store Your dates in Array and then use array_reverse() PHP Function to get the result in reverse order.
array_reverse — Return an array with elements in reverse order
Reverse array values while keeping keys
Try this:
$select_record = mysqli_query($con, "select * from table order by date DESC limit 5");
// Sort in chronological order.
usort($select_record, function($a, $b) {
return strcmp($a['db'], $b['db']);
});
while($row=mysqli_fetch_array($select_record)){
$date = $row['date'];
echo "<tr><td>$date<br></td></tr>";
The simple solution would be to extract the rows and the reverse the list in PHP land. This would be my solution in your simple case based on the result size.
If you really want to do it without having to store the full result in PHP land you could do it with a sub-select. This would mean replacing your query expression with:
$select_record = mysqli_query($con, "SELECT * FROM (select * from table order by date DESC limit 5) AS result ORDER BY date");
But I would think this to be less maintainable than just reversing the result in PHP.
You can also save your result in array. Then you can use sort($array);
PHP function Sort

count date per month , per year on database with date format with CodeIgniter

how to calculate the amount of data in 1bulan / 1 year on the basis of the date in the database based on the date format?i am using codeigniter
Example
date 2016-02-10
2016-05-19
2016-07-20
2016-02-30
2016-05-20
2016-05-21
Result count
data on Mounth Feb = 2
data on Mounth May = 3
data on Mounth Jul = 1
This My script
<?php
$sql = "SELECT * FROM tbcounter ";
$get_monthly = " WHERE date LIKE '".date("Y-m")."%'";
$monthly = mysql_num_rows(mysql_query($sql . $get_monthly));
echo $monthly;
?>
You can use DATE_FORMAT(date_column,'desired_output') as in this example:-
You can read about date function on http://php.net/manual/en/function.date.php
$date_variable = date("Y-m",strtotime('last month')); //prints 2016-01
echo $this->db->get_where("tbcounter",array("DATE_FORMAT(`date`,'%Y-%m')"=> $date_variable ))->num_rows();
This is demo code :)
For Counting data per year and per month you can use
GROUP BY YEAR(date), MONTH(date)
In your query.
Example :
SELECT count( * )
FROM `TableNAme`
GROUP BY YEAR( `Date` )
LIMIT 0 , 30
SELECT count( * )
FROM `TableNAme`
GROUP BY MONTH( `Date` )
LIMIT 0 , 30
Here Date is your column name in table.

php query returns missing data

I have a problem with my php query for getting data. Let me explain what I want. I have a database which saves the active users for some hours in a day. For example 01-01-2012 13:00
active = 5 01-01-2012 14:00 active = 10. My php query should make an array which contains 2 columns which are date and active. But date must be like 01-01-2012 withour hours. So I grouped them as date2 but I couldn't find the active(sum) for each days. Here is my query which doesn't give the right active sums.
$query2 = mysql_query("SELECT DATE_FORMAT(date, '%Y-%m-%d') AS date2, SUM(active) FROM hit WHERE game= '".$game."' AND source = '".$source."' AND date > '".$dateFrom."' AND date < '".$dateTo."' GROUP BY date2 ORDER BY date2");
while($tuple= mysql_fetch_array($query2)){
$myArr[] = $tuple;
}
print_r($myArr);
You need to alias SUM(active) and GROUP BY date. If date is a datetime, you can GROUP BY DATE(date). Also, be careful with reserved words and make sure to use tick marks where necessary.
Further, if you are looking for an inclusive date range, you should know that when you send 2012-10-03, it is actually 2012-10-03 00:00:00 and any records between 00:00:00 and 23:59:59 will be ignored.
Lastly, you should stop using mysql_ functions as they are being deprecated.
This query should work:
$query2 = mysql_query("
SELECT DATE_FORMAT(`date`, '%Y-%m-%d') AS date2, SUM(active) AS active
FROM hit
WHERE game= '".$game."' AND source = '".$source."'
AND `date` > DATE_SUB('".$dateFrom."', INTERVAL 1 SECOND)
AND `date` < DATE_ADD('".$dateTo."', INTERVAL 1 DAY)
GROUP BY DATE(`date`)
ORDER BY `date`");
$i = 0;
while($tuple= mysql_fetch_array($query2)){
$myArr[$i][date2] = $tuple[date2];
$myArr[$i][active] = $tuple[active];
$i++;
}
print_r($myArr);
Your array ($myArr) would then look something like:
Array
(
[0] => Array
(
[date2] => 2012-10-03
[active] => 5
)
)

Categories