Run a MySQL query if a week has passed - php

First of all I am a beginner, and I don't want anybody to write code for me. I would just like a bit of a hint from a more experienced developer.
I have a video site, what loads videos from another website with XML and saves info about the videos in the database. What I would like to do is that if a week is passed, automatically run the insert query.
I never did this before and never worked with time functions like this. So please could someone show his plan how he would do it? So no code, just explain the process.

I'd recommend setting up a cron: http://en.wikipedia.org/wiki/Cron

I dont think this is a coding-related problem. Tasking can be achieved by using cron.
Cron is a task scheduler, which when its available for your hosting, can be accessed at the hosting control panel. What is your host ?

You could use Cronjobs.

What do you want to do with the data in the week in between? I hope you're not hoping to keep a process running for a week and then execute the insert.
You could do something like load the XML and save it in the database, setting an active column to 0. You save the timestamp at the moment the insert is executed.
Meanwhile, using cron, you let a script run every X minutes or hours, checking the database for items that have been inactive for a week, and then updating them to become active.

You can use the time() function. It returns the number of seconds since January, 1st, 1970.
Then, for example, you take the time at t = 0.
When time() - t > a week (= 3600 * 24 * 7 seconds), you know a week has passed by.

Related

Handling time in PHP/SQL

I'm doing a school project in which I have to put news in an SQL database and, when a certain time passes (around a week or so) automatically edit the database to notify that a specific piece of news is no more active.
For example, I put on a news on monday, and I want it to automatically disappear (or appear as "closed") on the morning after.
So, what I would need is a PHP function (or an SQL one) that automatically starts with a specific timeout and edit the database.
Does anyone know something like that?
Thank you in advance for your help
PS I'm using PHP 5.3.10 and SQL 3.4.10 and I'm stick to them because they're installed on my lab computers
I don't think so. You would use a cron script or something similar to do this on a timer - but this is the wrong approach anyway.
What you need to do is add a time constraint to your SQL. So that your SQL "gets all the news articles for the last 7 days" or whatever
You can do this as follows:
SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK)
That way every time a user goes to your page, they will get all the records within a week of the current time. And you don't have to delete anything.
Remember the PHP and SQL query are only run when the website is refreshed. Hope that makes sense.

How to launch a php script 12 hours after each user triggered event

Any of the users can trigger an event, as many times they wish. Each time this event is triggered, a row in a mysql table is created with the timestamp, their userid and other useful information. What I need to do is launch a script which runs exactly 12 hours after the event is triggered i.e. for each row in the table.
How can I achieve this in an automated and efficient fashion?
You could use a cron job which every minute launches the script.
In the script you should first fetch the row(s) and check if it's OK to run (if 12 hours passed) then continue, else stop.
I don't know if this will be very efficient, it depends on your number of entries in the database, but technically it's not expensive to just check if the current date matches a date fetched from the database + 12 hrs, I cannot say more because you didn't give too much details about your data.
You'd probably be better off with a cronjob
http://en.wikipedia.org/wiki/Cron
Potentially, you could look into MySQL event scheduler. Although It might not fit your needs, hard to really tell on the details given
http://dev.mysql.com/doc/refman/5.1/en/events.html
something like
CREATE EVENT myTimedEvent ON SCHEDULE EVERY INTERVAL 5 minutes DO CALL updateRows();
updateRows checks your criteria (12hours ago), if it is, perform whatever action you want to do. This requires your MySQL to be # version 5.1+ however
You would probably best have a cron job which runs every minute and checks for any rows in the database > 12 hours old that have not yet been processed the script and process them. This wont give you EXACTLY a 12 hour difference, but would give you a difference within a minute of that.
You would probably also want to make sure that script would be able to run within a few seconds such that you don't have overlap of the script running twice at the same time.
This could be done using CronJobs. If you have root access to your Server or a server administration toolkit that offers cronjob managment you would do it on your server. otherwise use an online cronjob service (google for cronjob online).
the cronjob then triggers a php script on your server in your defined interval, like every minute or every 5 minutes.
this script then selects all rows from your mysql table which are older then 12 hours (WHERE timestamp <= NOW() - INTERVAL 12 hour ) and performs your desired actions on each result and delete the result from the table (or mark it done),
just make sure that the fetching and the actions itself are faster than your cronjob interval, otherwise you would have two or more scripts working on the same rows.
The easy way for me is to make the page head contains
<head>
<meta http-equiv="refresh" content="43200"> <!-- 43200 for (12 hours × 60 mintes × 60 seconds) -->
</head>
This method is very helpful to avoid server time out, which you can't avoid if you are using only PHP code
Important if you start the script using submit button, it's recommended to make the form action="other_page" not the same page, and sure you should save your input values as cookie using setcookie function and grab it as a variable in the action page using $cookieVar = $_COOKIE['the_cookie_name'] ;
You may need to increase or decrease the $cookieVar value and update the value again using setcookie every time your head code http-equiv do the refresh automatically after the specific seconds (43200 in our example) depends on what you want to do
Note that if you make your action start automatically without pressing submit button you can do the action in the same page.
I did that idea before, I had 180,000 images in one folder and the server didn't allow me to download it all because it was showing me only first 7998 images, so I create a script to zip each 1000 image in a file outside the images folder and to avoid time out, I made the code refresh each 60 second , finally I got only 180 zip file :)

calendar Question with PHP, reading your computer calendar

So I am really stumped because I have basic ideas but I am looking for some of your expertise.
What I am trying to do: I want to basically write an app using Twilio which you dont really need to know about because that is another issue. What that app does is call on a php file in my web host and "triggers the php code"
What I need help with here is how can I keep record in php of the calendar of the week for my computer. What I mean by that is if someone like an admin has a specific code that I have written for them, and that code runs automatically all week, but a specific week they dont want that code to run, instead they want a different code to run that week. How can I use php to find when a week has ended or keep track of the week using that calendar in bottom right of your computer screen so that my program will know after an admin wants a different code run from the usual code that the week is over no need to run that admin irregular code any more go back to your usual automated running code.
If you still dont know what I am talking. I will try to explain more. Think of 2 separate codes. One Custom and the other automated. The automated runs all the time automatically. But one day the admin chooses for that week he doesnt want to follow the regular shcedule of running the automated code as usual, instead for that week he would like to run the custom code and after the week is over go back to running the automated code as usual.
I hope that makes it more clear. I know that in PHP gives the date. But I really need expert opinion on how to do this.
Generally for something like this, I'd generate a "nextrun_datetime" for each and every script/user combination. By default it would have a repeat interval, in your case, 7 days.
If a user doesn't want to run it this week, they can "push" it out N days and the normal update interval would apply afterwards. To get the one-time shot, I'd allow an update interval of 0 or -1 to denote that.
With this sort of thing, whenever a script is updated (or saved, run, rescheduled), you can calculate the next date if there is one. From there, it's a relatively simple cron job that should check the last N minutes for any scripts to be run.
Unless your client machines are running on a completely different calendar than the server, why bother with wondering what the client's date is? Unless the client and server are in different time zones, the client date is going to be the same as the server date, except for a few hours around midnight.
As well, why depend on the client to trigger the server-side code? If this is a regularly occuring thing, use cron or whatever's available on the server to run the code automatically. If an admin wants to override WHICH code gets run, then you can provide an interface to change what's executed. Click a button on a site and a flag is set somewhere that tells the timed job to run script B instead of script A.
I've done something similar. Based on the day (e.g. monday, sunday) I would do something different in php.
this is how I did it:
$today = date('w');
if ($today== 0){
//its sunday
exec('rmdir C:\myApp\oldLogs');
}
else{
echo '1 -> monday, 2-> tuesday etc...'
}
you can also make a date from a string for example
$date = strtotime("8 days ago 14:00");
/*
or "Monday next week", "+1 week 2 days 4 hours 2 seconds","yesterday noon","10 September 2000" etc...
*/

Changing the status of a field in PHP after a period of time

For example I made a reservation for a restaurant and it expires in 24 hours. In the reservation table of the db (MySQL), how do I automatically update the status to expired after 24 hours? What approach would you guys suggest? Thanks in advance!
Don't really know the problem you're trying to handle but I'd store the timestamp when the reservation was made and have a field which stores after what interval from the point reservation was made does it expire (24 hrs in your case) and that's it. The rest should be handled at the point where you read/display that information.
Besides if you still really want to CHANGE the value in DB go for a cron that regularly updates the DB
Running periodical tasks is usually done with cron.
Here are some instructions how to use it on drupal (which is php/mysql)
Use cron like Unreason said or MySQL events, see Create event.
using cron can be liitle difficult
just run update query by comparing timestamp value with your time limit.
it will work.
I would suggest the following two methods.
To run a cookie at the background and check it out if the time (here in this case 24hrs) ran out or not..
Store the entry in the database with DATETIME type. As we check whether the user logged in or not with session variables. In the similar way for every click in the site, call a function to check whether the time is lapsed or not.

PHP game update

Say I have a game in PHP which is a money making game and everyday the prices on items change on the market.
How would I make it so the prices in the database are automatically updated each day? Would I install a program on the server that detects when it has gone 24 hours then runs a PHP file which does the updating? Or os there another way?
Edit:
The thing is guys, I don't actually own the server I rent it from a hosting company so I don't really have access the the command line :s
Thanks, Stanni
Assuming you're on a Unix system, you should setup a daily cronjob. To do this, run "crontab -e" and enter something like:
9 21 * * * /path/to/your/script
This will run at 21:09 every day.
Since you probably don't have access to cron either what I would do is check how much time has passed everytime someone loads a page. If 24 hours have passed then call your update function. If 48 hours have passed then call it twice. If no one loads the page then it doesn't matter if the update function has been called or not because no one is looking ;)
Or you could setup a computer at home to call your update.php remotely every 24 hours. You can do that with a cron job and wget or if you're using windows you could use the task scheduler.
I think the first option will work the best. Call your update function every page load and only update when the 24 hour mark has passed. If you write it correctly it doesn't matter if it gets updated at the exact 24 hour mark.
If you don't have access to the commandline, you could add a 1x1 image to the website which calls a php script which checks if there needs something be updated.
something like
<img style="width: 1px; height: 1px; visibility: hidden" src="cron.php">
In cron.php you check if the data needs to be updated.
You want to set up a "cron job", or a PHP file that runs at a certain interval you set.
Check out this article for more information.
The best part about cron jobs is that you are not limited to the small subset of functionality available in say, stored procedures. You can use whatever logic you like! :)
Use webcron :)
http://www.webcron.org/index.php?lang=en
Or here is a good list:
http://www.onlinecronservices.com/
If you have a script that updates the prices and all you want to do is run it every day, use Cron (linux) or at command (windows).
How could you not 'have access to the command line'? I can't think of any host that doesn't allow ssh access. Having access to cron is a different story, but they SHOULD allow this, also. If they don't - find a new host!
Forget all that. There is no reason to do anything like that.
All you have to do is check each time someone calls the webpage. You keep track of the date and when the current date no longer matches your variable then you fire off the thing that gets new data. Bam! Of course that's not very scalable but it's fine for a small game.
I think that you can make a function that gets called every time a page is accessed, and verifies if the update took place, checking against a database.
So in a quick pseudo code:
function verify_often(){
if (last_update_in_db() != today() ){
update_db();
run_periodic_function();
}
return 0;
}
This method requires only the classic PHP & MySQL combination.
I couldn't work out how to reply to alex's answer but I wish to mention something that they said. When they said "check how much time has passed everytime someone loads a page" I feel that you don't need to check it every time the page is loaded. The better way of doing it would be to check when a user logs in. If it goes over 24 hours while users are still logged in it will not matter for the described scenario. The next time someone logs in the prices of items will change.

Categories