I am trying to count the occurrences of certain dates in my MySQL table using a PHP while loop and place the date and number of repetitions in an array. I am able to properly add the date to the array, but I cannot seem to add the number of repetitions to it.
Example:
function counter() {
//The 'timestamp' column uses the MySQL timestamp type
$query = mysql_query("SELECT timestamp FROM table1 ORDER BY timestamp DESC");
$date_c;
$counter = 0;
$date_array();
while($row = mysql_fetch_array($query)) {
//gets the year, month, and day from the timestamp
$year = substr($row['timestamp'], 0, 4);
$month = substr($row['timestamp'], 5, 2);
$day = substr($row['timestamp'], 8, 2);
$date = $month.'/'.$day.'/'.$year;
if($date == $date_c) {
$counter += 1;
} else {
array_push($date_array, $date, $counter);
$counter = 0;
}
$date_c = $date;
However, when I echo part of the array the counter does not update. Here is an example using the first repeated date in table1:
>>> echo $date;
06/15/2012
>>> echo $counter;
25
>>> echo $date_array[0];
06/15/2012
>>> echo $date_array[1];
0
I have played around with this for a while but I can't seem to find my error. Does anyone know what I am doing wrong?
Is there anything else you want to do with those rows? Because this seems easier to me:
SELECT DATE_FORMAT(timestamp,'%m/%d/%Y') as 'date', COUNT(*) as 'count'
FROM table1
GROUP BY DATE_FORMAT(timestamp,'%m/%d/%Y')
ORDER BY timestamp DESC
... and the problem in the php code might be the last date / count isn't pushed to $date_array (the array_push will have to run once more after the while loop is finished, if the last iteration did NOT push a counter on the array.....)
Agreed with Wrikken that you can get the count of unique dates in SQL, rather than needing to do it in PHP.
However, if you do want to count the instances of each date, I would use the associative array feature of arrays in PHP. So something like:
$query = mysql_query("SELECT timestamp FROM table1");
$date_array = array();
while($row = mysql_fetch_array($query)) {
$year = substr($row['timestamp'], 0, 4);
$month = substr($row['timestamp'], 5, 2);
$day = substr($row['timestamp'], 8, 2);
$date = $month.'/'.$day.'/'.$year;
// Using the # symbol to suppress warnings for missing index
# $date_array[$date]++;
}
print_r($date_array);
At the end of that loop, $date_array is an associative array with the date as the key, and the number of occurrences as the value.
Related
I have problem getting the year
I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015
$selectmemberpaid = mysql_query("SELECT
memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM
tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =
.profile_id WHERE memberid='201400001'");
That is my query..
and this is my while loop
while ($rows = mysql_fetch_assoc($selectmemberpaid)) {
# code...
$dateTimestamp = strtotime($rows['StartDate']);
$year = date("Y", $dateTimestamp);
}
You can get the year from a date string by doing something like this:
$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;
Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).
I'm not sure I understand what you're asking but:
Query!
$rest = substr(date('d-m-Y'), 6);
$rep = $idz->query("SELECT * FROM stack1 where SUBSTR(date_depart, 6) < $rest
order by SUBSTR(date_depart,6) desc limit 3");
while ($row = $rep->fetch())
{
echo $row['date_depart'];
//echo "<br>";
}
$rep->closeCursor();
Result
Starting with the number 9 and using php, I would like to be able to count up from there, and echo out the next number in increments of 1.
So, number 9, then after 1 month the number would change to 10, then another month 11, then 12 etc., with no maximum number/stop point.
How can I accomplish this? So far I have the below code.
$number = 9;
$output = $number + 1;
echo $output;
Is there a way to set this to increase once a month?
You can do this with the PHP date()-function. This is one example of doing it if you are not dependent on the day of the month, but adding day functionality is possible and should be quit easy.
$startNumber = 9;
$startYear = 2015;
$startMonth = 9;
$currentYear = intval( date( "Y" ) );
$currentMonth = intval( date( "n" ) );
$monthsToAdd = ( ( $currentYear - $startYear ) * 12 )
+ ( $currentMonth - $startMonth );
echo $startNumber + $monthsToAdd;
From your question, I'd say:
$number = 9;
$output = date('n') + $number;
echo $output;
But that depends on what you are trying to accomplish. You can also wrap the number around the date() with a modulo.
However this is nothing random. If you want to create a random number every month like your topic suggests, use the month as the random seed.
srand(date('n'));
$number = rand();
a very inefficient way would be
<?php
function increm($duration){
while ($i<$duration) {
$i++;
}
return true;
}
$number = 9;
$start = time();
$i = 0;
while (1){
increm(3600*24*30);
$i++;
// Do your code
}
?>
this script would have to be run continuously for months.
A better way would be
<?php
$number = 9;
if(!file_exists('date.txt')){
$date=date('n');
file_put_contents( (string)time());
$date = 0;
}
else{
$date= file_get_contents('date.txt');
$date= date()-(int)$date;
$date= floor($date/(24*3600*30));
}
// do whatever you may
?>
But this script would increase it whenever called as the first open date would be stored. Will work forever (till UNIX can timestamp).
for this purpose you have to store the number in the database, compare with current unix timestamp and update it when the new month is reached.
2 database columns: count_month int(10) and next_month int(10) where next_month will contain the unix timestamp of the first day of the next month. you can run it with cronjobs or on production.
<?php
$now = strtotime("now");
$next_month = strtotime("first day of next month");
if ($query = $dbconnect->prepare("SELECT next_month FROM table1")) {
$query->execute();
$query->bind_result($compare_time);
$query->store_result();
$row_count = $query->num_rows;
if ($row_count > 0) {
while ($query->fetch()) {
if ($compare_time < $now) { // you reached the 1th of the next month time to update
if ($query2 = $dbconnect->prepare("UPDATE table1 SET count_month=count_month +1, next_month=?")) {
$query2->bind_param('i', $next_month);
$query2->execute();
$query2->close();
}
}
}
}
$query->free_result();
$query->close();
}
?>
I'm building an array of the number of calls I have for a particular client from a mysql db on a running list of the last 30 days. The code I have so far works for adding the days that have calls to the array but I need a show a '0' for the days that have no calls (no entries in the db). Here is me code so far:
$query="SELECT COUNT(*) FROM my_db WHERE client_phone='clint_phone#' GROUP BY calldate";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_row($result)) {
$data[] = $row[0];
}
I just need a way to show if today I had 30 calls and yesterday I had 0, I need it to show [30,0]. What I have only would show [30].
EDIT * I have a mysql db will columns client_phone, calldate. Im looking to build a graph using the data in an array. Each point of the graph will represent a day and the number of calls for that client on that day. Im building the above query to populate that array. I'm trying to count backwards thirty days and feed the total calls for each day into the array.
EDIT 2* I've got it almost there. I'm getting a problem in the 'foreach' area. Below is the code with two print_r()'s to dump the array. The first one looks good, but the second one shows some array entries getting over-written that shouldn't be:
$query="SELECT calldate, COUNT(*) FROM my_db WHERE client_phone='phone#' and calldate>='20130101' AND calldate<='20130107' GROUP BY calldate ORDER BY calldate";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['calldate']] = $row[1];
}
$startDate = '20130101';
$endDate = '20130107';
$dates = array();
for($current = $startDate; $current != $endDate; $current = date('Ymd', strtotime("$current +1 day"))) {
$dates[] = $current;
}
$dates[] = $endDate;
print_r ($data);
echo "<br />";
foreach($dates as $date){
if (in_array($date, $data)) {
// that date was found in your db_date array(therefore had queries)
}else{
$data[$date] = 0; //date was not found in your db_array so we set that date with no queries to zero
}
}
print_r ($data);
I run this in a browser and I get this:
Array ( [20130101] => 1 [20130104] => 6 [20130105] => 2 [20130106] => 1 [20130107] => 3 )
Array ( [20130101] => 0 [20130104] => 0 [20130105] => 0 [20130106] => 0 [20130107] => 0 [20130102] => 0 [20130103] => 0 )
The top output looks good, just missing a zero assigned to dates not in the data[] array. The second array has zero's in the missing dates, but other overwrited that shouldn't have been.
Thanks for any help!
Finding every date that is in that timespan and doing a task for that does not really that standard of a solution. But depending if your host allows cron-tasks; if you were able to use cron tasks to automatically insert a 0 into your database at 11:59pm for that date if no querys were made that day; you could simply extract all dates.
If you do not want to do it with cron tasks I think you can manage it this way...
$startDate = '2009-01-28';
$endDate = '2009-02-04';
$dates = array();
for($current = $startDate; $current != $endDate; $current = date('Y-m-d', strtotime("$current +1 day"))) {
$dates[] = $current;
$dates[] = $endDate;
}
then do this
foreach($dates as $date){
if (array_key_exists($date, $data)) {
// that date was found in your db_date array(therefore had queries)
}else{
$data[$date] = 0; //date was not found in your db_array so we set that date with no queries to zero
}
}
This may need some minor adjustments because I have not tested it; but this should work; if not something very close to it should. Hope this helps.
I found this great function on SO whilst looking for a way to generate random dates between two fixed timestamps:
function randomDate($start_date, $end_date)
{
// Convert to timestamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
Source and credit
but I am looking for a way for the dates to be generated in order (start date to end date) as I have used it to generate dates to insert into a database.
The problem is my posts are ORDER BY id DESC and using the function "as is" being that they are random the dates end up out of sync.
ie:
post id 4 - date = 2010-07-11 14:14:10
post id 3 - date = 2012-02-22 18:23:21
post id 2 - date = 2011-03-17 13:52:47
post id 1 - date = 2011-08-14 15:33:50
and I need them to be in sync with the post id.
Now your thinking why not change the query to ORDER BY date DESC instead? ...well that would mess up 99% of code I have already written as there are other columns/rows dependent on it being ORDER BY id DESC and so ordering the dates when being inserted into the database is the only solution.
update:
this is what I tried using madfriend code but all dates are the same where have I gone wrong?
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
$update = "UPDATE foo SET date='{$date}'";
mysql_query($update);
}
plus getting
Notice: Undefined variable: startdate
I'm not quite sure whether you are talking about creation or modification of existing rows.
Updates: basic idea here is quite simple. First, count number of posts with SELECT COUNT(*) FROM your_posts_table query. After that:
// $num is number of posts
$dates = array();
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates); // Sort dates in ascending order
while($date = array_shift($dates)) {
// now $date won't be lower than it was in previous iterations.
// use it to update your table
}
Insertions: If you are talking about insertions and want to make latest post date random but biggest, here's what you do:
First, select last added post date.
Second, call randomDate with $startdate set to the date of last added post.
Last, insert new row with this date.
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
This query updates all rows in one go:
$update = "UPDATE foo SET date='{$date}' ";
mysql_query($update);
}
Probably were wanting to use
$update = "update foo set date='{$date}' where id = (select id from foo where date is not null order by id limit 1)";
(for that to work you need to set each date in the db to null before you start updating: update foo set date=null)
Also you shouldn't be using myslq_query..
I use PHP to perform SQL to pull out some data from my database between a date range. The dates are stored as date in the relation:
$from = "2011-08-11";
$to = "2011 - 08- 25";
$query = mysql_query("SELECT date FROM `entries` WHERE date BETWEEN '$from' AND '$to' ORDER BY date ASC");
I would like to find the earliest date pulled from the relation.
If the query is successful, I store the 'date' attribute in a php array called $dates. I thought I could iterate over this $dates and compare the $date values after converting them into dates.
if($query){
$dates = array();
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
for($i = 1; $i < count($dates); $i++){
if($dates[i] < $min){
$min = $dates[i];
}
}
This does not work however...It prints random values....Perhaps there is a much simpler way to do this and I am overcomplicating matters...
HEEEELLLP!!
If you order your query, then it will be the first (or the last) row in you're query. So you wouldn't need to find it.
Instead of
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
you should use
$min = date("%Y-%m-%d", strtotime($dates[0]));
The simplest way is to use the first date since you know it is already the earliest due to ASC in your SQL statement. After you read the rows into your array, just use the first element.
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$earliest_date = $dates[0];
If all you want to do is find just the earliest date, and you don't care about the rest, you could use the aggregate function min() in your query like so:
SELECT MIN(date) AS earliest FROM `entries` WHERE date BETWEEN '$from' AND '$to'
Then just grab the earliest column from the result set in your php code.
Convert the dates to numbers and sort the array?
Take what you have (lines 1-5),
foreach ($dates as $date) {
// convert each date from "YYYY-MM-DD" to "YYYYMMMDD" and turn it into an int
$date = intval(str_replace("-", "", $date));
}
// sort the array from lowest to highest
asort($dates);
// the minimum is the first item in the array
$minint = $date[0];
// convert back into "YYYY-MM-DD" format
$min = substr($minint, 0, 4) . "-" . substr($minint, 4, 6) . "-" . substr($minint, 6);