I have a table called profile_views on my site that counts how many times a person views a users profile. What i am trying to do is let users see how many visiters they've had to their profile in that week, and every week I on Monday I want the table to be emptied so the count can restart from 0.
I am trying to create a php if statement that says every week on monday carry out the delete mysql query. I have got it to perform only if the day is monday, however I am trying to find a way to execute it only once, preferably at 00:00AM monday morning, because I dont want it deleting results in the table constantly throughout the whole of monday.
<?php
$today=date(l); // Find what today is? using date function
// If today is Monday displays message "Today is Monday" and displays image1.gif
if($today==Tuesday) { // Compare $today with name of the day.
$result = mysql_query("DELETE FROM ptb_profile_views;")
or die(mysql_error());
}
?>
What you are looking for is named cron - use it to invoke your PHP script on desired weekday at desired time.
Setup Cron - based on our requirement
http://www.sophos.com/en-us/support/knowledgebase/12176.aspx
http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
you could set up a cron job to automatically execute the script, but a better way (the way I do it) is to just leave the entries in the database and when displaying the number of visitors in the last week, change your query to return only entries within the last week. this might be much easier.
A method without cron jobs:
You can set a variable $ran and store it somewhere (maybe in a file?). Then every Monday, run and store the $ran into the file as true.
If it's any other day, set $ran back to false. This will ensure that the script will only run on Monday, and only run once.
Related
I want a functionality that insert data every month...
I have some idea to implement this that is as follow....
When User Create 'INVOICE' at that time the 'INVOICE' automatically generated every next month once user create it.
Let have some code...
INSERT INTO INVOICE (id,user,date,bill_money) VALUES ('','XYZ','25/03/2015','100');
this one works very well now every next month same entry should be automatically inserted..
For that i have logic that when user log-in into portal at that time first i have retrieve user's last log-in and from that date to currently log-in date i try to insert those data which are 30 days old data...
I select next day(date) after user's last log-in date and then Check for every that up to current day(date).
To retrieve user last log-in date
echo $this->session->userdata('name')
To check interval lastlogindate() + INTERVAL 30 DAY == NOW()
If this becomes true then then insert data
But here problem is that i want to implement for month, quater, year
Is this flow is better or there can be another way to do this..??
I heard about cron job and MySQL Event which one is best in this two and how they are working which one is effective performance wise...
I want suggestion on this. Thank you....
If you want a recurring invoice. Just store the invoice once and schedule a cron job that will run daily at scheduled time. Cron job will run your php script to do whatever you want to do like : store invoice in db or email it to user. If you don't know about cron jobs, basics can be found in this answer : How to create cron job using PHP?
EDIT : you will have to schedule cron job using cli
Mysql events
I think this is better for me i haven't use Cron Job...
for Mysql event checkout syntax and have a fun...
I'm new to PHP and I'm hoping to make a script where a user will get a "coin" every hour that they go on the page. For instance, if a user logs in twice during the same hour, they will only get one coin. But if they refresh the page during the next hour, they get another coin. However, they do not get coins when they do not refresh the page, even if many hours go by.
How would I even start going about doing this? Any help would be extremely appreciated.
Easy... :) If you are using MySQL or something to store the coins, get the time too, when the coin was credited. And each time the page is called, check the time. A pseudo code would be like this:
load(coins);
timeDiff = timeNow - timeLastCredited;
if (timeDiff > 1 hour)
coins++;
save(coins);
In case of PHP, I guess you may do like this:
$coins = getCoins(); // Assuming this function will load the current coins count from DB.
$lastCredit = getLastCoinCreditedTime(); // Should return a DateTime integer.
$timeDiff = microtime() - strtotime($lastCredit);
if ($timeDiff > 60*60*60*1000)
saveCoins($coins+1); // Assuming this function saves the new number of coins.
I'd do it this way:
On each page load (refresh, login, whatever), check to see if the user has already received a coin for the current hour. To do this, you need to know what the current hour is:
$hour = (new DateTime())->format("Y-m-d-h");
This will give a value like "2013-03-25-11" during the 11:00 hour. I'm including the date, since we don't to want skip giving a coin in, say, the 11 o'clock hour just because they were online yesterday at 11:05.
Then you can either:
Add one to their coin total whenever you have a new $hour value (ie. it's not recorded in your database) and save the $hour value, or
Save the $hour value in the database and count the total number of coins earned with a query like SELECT COUNT(DISTINCT hour) FROM table;
The first approach is useful if they're spending the coins on something (ie. you can add/subtract from their "coin account"); the second is useful if you just want a grand total of the number of coins (ie. the total number earned, ever).
I'm going to assume that you have a users table in a database.
If that is the case, you can use a column in the database to update the latest time that a user has gone on the page with php and a query on that page. Then you can set up a cron job that runs every hour that will query the users table and see if the user has viewed the page within the last hour. If the user has viewed the page within the last hour, increment the amount of coins associated with that user.
How can I decrement a MySQL field every day?
Such as:
field1= 30 and after 24hours -> field1=29 until 0.
You'd probably be better off placing the current date in the database, and then use DATEDIFF to get the days since. You could even do 30 - DATEDIFF and then have the number the way you want it.
You can execute a Unix cron job (there's some informations here) which will execute your PHP script every day.
I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id
I'd like to know the best way to implement in PHP a counter that, having been incremented by some events on the server during a day, would be reset to zero with a new day coming, i.e at midnight. Probably comparing the date associated with the last value of the counter with the current date would make it reset?
EDIT: What if the counter gets reset the moment when it's going to be incremented provided that the code somehow figures out that the last time the counter was incremented was yesterday or a day earlier? It would be good enough.
Are you storing your counter in a database? If so, you might just want to store the date of the last change along with it. Let me assume you have a table counters(name, value, date), then the following pseudo-code might give you an idea:
$counter_id='herpderp';
$today = date('dMY');
$date, $value = query("SELECT date, value FROM counters where name='$counter_id'");
if ($date!=$today) {
$value = 0;
query("UPDATE counters SET date='$today', value=1 WHERE name='$counter_id' AND date='$date'");
} else {
query("UPDATE counters value=value+1 WHERE name='$counter_id' AND date='$date'");
}
echo $value;
Depending on your server you're either going to either be able to implement a Scheduled Task (Windows) or CRON Job (Linux). This will be what allows your script to execute at a specific time of day (or night).
As for the counter, you can implement that in a few ways. For data integrity and security, I'd store the value in a database. To increment, fetch the value and increment it (there are also some ways, depending on your DBMS, to do this with a single SQL query). Otherwise you could always edit a configuration file with I/O commands in PHP.
Setting up the CRON Job / Scheduled Task
If you give me more information on your server configuration I can give you specific tutorials on where you can find out how to set up your task.
Once you've figured it out, you'll want to call a specific script. Your script in PHP can be set up as follows:
Compare the current D/M/Y to the previous days, most likely stored in your database or configuration file. If this checks out, update your database/file performing whatever analytic actions you deem fit.