How to update date automatically in mysql via php request [duplicate] - php

I have a mysql table and I want it to be "emptied" every night at midnight. I have searched for an answer on the web and came across nothing that seemed to help me. I had this idea of using javascript to get the current time and then run an if statement and see if it is equal to midnight and if it was to execute a php script that deleted the information.
Javascript:
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
if(t == 12:00:00 AM){
$.ajax({
URL: 'delete.php';
});
};
};
delete.php:
<?php
require 'connect.php';
mysql_query("DELETE * FROM messages;");
?>
I have tested this by setting the time in the if statement to a time a few minutes ahead of my actual time and it does not work.

Implementing your own event scheduler, especially as a web page using JavaScript is a bad idea.
Use for that either
a cron job to run DELETE statement through the mysql command line interface
/path/to/mysql -u<user> -p"<password>" <db_name> -e "delete from messages"
or a MySQL event, e.g.
CREATE EVENT delete_messages_at_midnight 
ON SCHEDULE EVERY 1 DAY STARTS CURDATE() + INTERVAL 1 DAY
DO DELETE FROM messages;
If you go with MySQL event approach:
use SHOW PROCESSLIST to check if the event scheduler is enabled. If it's ON you should see a process "Daemon" by user "event_scheduler".
use SET GLOBAL event_scheduler = ON;to enable the scheduler if it's currently not enabled.
More on configuring event scheduler read here

Related

Multiple includes in PHP script called via command line

I'm working on creating some scheduled tasks that perform system maintenance on my database (i.e. inactive user cleanup, data archiving, etc.) and also generate/email automated data reporting.
Currently I have it setup so that each task is its own file and there is a master file that calls the appropriate tasks.
For example:
run_daily.php
<?php
define('INCLUDE_CHECK',true);
require $_SERVER['DOCUMENT_ROOT'].'/db/connect.db.php';
require $_SERVER['DOCUMENT_ROOT'].'/includes/definitions.inc.php';
$get_dailyTasks = mysql_query("SELECT task_name FROM task_scheduler WHERE task_type='task' AND task_occurs='daily' AND task_active=1");
while(($dailyTasks = mysql_fetch_assoc($get_dailyTasks)))
{
include $schedule.'tasks/'$dailyTasks['task_name'].$tsk;
};
$get_dailyReports = mysql_query("SELECT task_name FROM task_scheduler WHERE task_type='report' AND task_occurs='daily' AND task_active=1");
while(($dailyReports = mysql_fetch_assoc($get_dailyReports)))
{
include $schedule.'reports/'.$dailyReports['task_name'].$rbf;
};
?>
user_cleanup.php
<?php
$disable_inactive = "UPDATE users SET enabled='no' WHERE (created < (CURDATE() - INTERVAL 3 MONTH) AND last_active IS NULL AND enabled='yes') OR (last_active < (CURDATE() - INTERVAL 3 MONTH) AND enabled='yes')";
mysql_query($disable_inactive);
?>
I'm attempting to set it up this way because I plan on having the master file run via command line and scheduled as a task scheduler job on the server. I will have access to modify the files as needed but I will not easily be able to change what is scheduled to run once it is setup. My thought was to schedule a master task and this would allow me to add/remove sub-tasks as needed.
The problem I'm running into though is that when I test everything via command line, the sub-task never seems to return control to the main task. After the first sub-task runs (regardless of how I order them) none of the other sub-tasks after it run.

PHP: Check mysql database every 10 seconds for any new rows

I am making a php chat and am starting the php checking database part. So when a user types something into the chat, it gets recorded in the MySQL database, how would I check the database every 10 seconds so that one user's chat would update with new messages from other users. I know that you can use an ajax request to a page with an interval, but I want the php to be on the same page, instead of having to use numerous pages. This is the code for checking the database
<?php
$con = mysqli_connect('host','user','pass','database');
$query = mysqli_query($con,"SELECT * FROM `messages`");
while ($row=mysqli_fetch_assoc($query)) {
$user = $row['user'];
$message = $row['message'];
echo 'User: ',$user,' Message: ',$message;
}
?>
Thanks in advance anyone!
Use MySQL Event Scheduler.
Below link will guide you through .
http://www.9lessons.info/2012/10/mysql-event-scheduler.html.
I think best option in your case .
AJAX is probably the simplest solution. You can perform an AJAX request on the same page your PHP code is executing on if you really want to.
(function check() {
$.get('mypage.php', function(data) {
doSomethingWith(data);
setTimeout(check, 5000); // every 5 seconds
});
})();
PHP doesn't have a setInterval function. While I'm sure you can use a crontask to automate it on the server, you can also achieve this with some simple Javascript.
The concept you are trying to achieve is known as Short Polling. What you want to do is to have a setInterval function in Javascript that constantly makes AJAX requests to your PHP file which performs the check to the database for new messages. Your PHP should return that information to your script where you can then simply populate the user's screen.
There is also Long Polling where you simply maintain the connection and have a setTimeout to wait for messages to come in. You can find more information yourself and if you have questions, you can come back here.
A good video about this:
https://www.youtube.com/watch?v=wHmSqFor1HU
Hope this helps.
This is what you need. We need set time for ajax auto reload. Don't put everything in one page. Because you must reload page to refresh data. That is bad solution.
Call jQuery Ajax Request Each X Minutes
Make a while for 30 seconds, and check the db every second, once you find a record the while is being broken, also it is being broken when 30 secs are expired.
$sec = 1;
while($sec <= 30) {
if(has record)
Send to the user;
$sec++;
sleep(one sec here);
}
Use sleep for 10 secs in order to check every 10 secs...

How do you write a program to automatically modify existing SQL database every x minutes?

I am a PHP/SQL novice user....Finishing off my first PHP website. The question is similar to the initial question found at:
http://forums.phpfreaks.com/topic/266235-modifying-database-after-a-set-time-limit/
but I did not completely understand the answer. Similar to that user, I have an entire column (called status) of a database (called challenge) that can take 3 values for status - 'inactive', 'pending', or 'active'. In the normal flow of website operations, User A will typically click a button (event 1) which creates a new row (with a unique *challenge_id*) in the database and triggers a status of 'pending' in that row. User B can change the status with other clicked buttons, which can set the status to 'inactive' or 'active'.
One undesirable scenario is where USER B does nothing (i.e., no event trigger). In this case, User A is unfortunately stuck, waiting for the status to change from 'pending' to either 'active' or 'inactive' before he/she can click and trigger the next event 1. This situation could occur for example if User B gets tired of the site and does not use it anymore, leaving 'pending' requests unanswered.
Clearly, I can manually alter the SQL, changing any 'pending' status to 'inactive' after a certain time limit. This would be fine at the beginning, but if the site ever became popular, this would take more time. Is there any way to write a non-PHP program to account for this 'no event trigger' scenario where all 'pending' status SQL entries are automatically altered after a certain time limit? Or can PHP do this? I tried writing a php script that would sweep the database every time any user logged in (note: *challenge_id* is created by an event triggered on a different PHP page):
<?php session_start();
if ((($_SESSION['role']) != SHA1('user')) && (($_SESSION['status']) != SHA1('active')))
{
header( 'Location: index.php' ) ;
session_destroy();
} else
include 'connect.php';
$_SESSION['login_id'];
$universaltime = time();
$sqlt = mysql_fetch_assoc(mysql_query("SELECT challenge.challengetime,
challenge.status FROM challenge"); //Selects an array of all values for challengetime
//and status for all users I presume
while ((($universaltime - $sqlt['challengetime']) > 1000) &&
($sqlt['status'] == 'pending'))
{
$sqlt1 = mysqli_query("UPDATE challenge SET $sqlt['status'] ='inactive'");
//Also tried with if instead of while
}
?>
I'm sure my code can be improved...any help would be appreciated greatly! Or do I need to use something other than PHP?
First of all your UPDATE statement is wrong. Assuming that challengetime is of int data type holding unix time values your UPDATE statements should look something like this
UPDATE challenge
SET status = 'inactive'
WHERE status = 'pending'
AND 1000 < UNIX_TIMESTAMP() - challengetime;
It can be and should be run on its own. You don't need to select anything prior to calling it.
Therefore you can change this part
$universaltime = time();
$sqlt = mysql_fetch_assoc(mysql_query("SELECT challenge.challengetime,
challenge.status FROM challenge"); //Selects an array of all values for challengetime
//and status for all users I presume
while ((($universaltime - $sqlt['challengetime']) > 1000) &&
($sqlt['status'] == 'pending'))
{
$sqlt1 = mysqli_query("UPDATE challenge SET $sqlt['status'] ='inactive'");
//Also tried with if instead of while
}
with just
$sql = "UPDATE challenge SET status = 'inactive' WHERE status = 'pending' AND 1000 < UNIX_TIMESTAMP() - challengetime";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO better error handling
}
Now to make it execute periodically on it own you don't necessarily need php. You can:
First option Use MySQL event.
To execute this statement every day at 11pm
CREATE EVENT change_status
ON SCHEDULE EVERY 1 DAY
STARTS CURDATE() + INTERVAL 23 HOUR
DO
UPDATE challenge
SET status = 'inactive'
WHERE status = 'pending'
AND 1000 < UNIX_TIMESTAMP() - challengetime;
Use SHOW PROCESSLIST to check if event scheduler is enabled. If it's ON you should see a process "Daemon" by user "event_scheduler".
Use SET GLOBAL event_scheduler = ON;to enable the scheduler if it's currently not enabled.
More on configuring event scheduler here
Second option Use crontab to invoke CLI mysql
/usr/local/mysql/bin/mysql -uuser -ppassword -e " UPDATE challenge SET status = 'inactive' WHERE status = 'pending' AND 1000 < UNIX_TIMESTAMP() - challengetime"
If your web & PHP server is running on Linux (which is often the case) and if the delay x is more than a few minutes (i.e. x>=5 minutes) then you could use crontab(1) and add a crontab(5) entry. Remember to use absolute paths there. That entry would run (periodically) some script (which you could code in PHP, but also in some other scripting language like Python or OCaml) which would update the MySQL database.

Run an indefinite PHP script for an hour. Restart every hour

I wrote a PHP script to pull tweets from the Twitter firehose and store them into a database. Ideally I want to just let it run so that it collects tweets over time, thus, it's wrapped in a while(1) loop.
This seems to be problematic because it's timing out. If I just run it in a browser, it won't run for more than 30 seconds before timing out and giving me a 324 Error.
Question: Is there a way that I can have it run for a certain amount of time (20 seconds), auto kill itself, then restart? All in a cron job (PS...I don't know how to write a cron job)?
Background: Site hosted on Godaddy. Would ideally like to run this on my hosting server there.
The Script:
<?php
$start = time();
$expAddress = "HOSTNAME";
$expUser = "USERNAME";
$expPwd = "PASSWORD";
$database = "DBNAME";
$opts = array(
'http' => array(
'method' => "POST",
'content' => 'keywords,go,here',
)
);
// Open connection to stream
$db = mysql_connect($expAddress, $expUser, $expPwd);
mysql_select_db($database, $db);
$context = stream_context_create($opts);
while (1) {
$instream = fopen('https://USERNAME:PASSWORD#stream.twitter.com/1/statuses/filter.json','r' ,false, $context);
while(! feof($instream)) {
if(time() - $start > 5) { // break after 5 seconds
break;
}
if(! ($line = stream_get_line($instream, 100000, "\n"))) {
continue;
}
else {
$tweet = json_decode($line);
// Clean before storing
// LOTS OF VARIABLES FOR BELOW...REMOVED FOR READABILITY
// Send to database
$ok = mysql_query("INSERT INTO tweets
(created_at, from_user, from_user_id, latitude, longitude, tweet_id, language_code,
place_name, profile_img_url, source, text, retweet_count, followers_count,
friends_count, listed_count, favorites_count)
VALUES
(NOW(), '$from_user', '$from_user_id', '$latitude', '$longitude', '$tweet_id', '$language_code',
'$place_name', '$profile_img_url', '$source', '$text', '$retweet_count', '$followers_count',
'$friends_count', '$listed_count', '$favorites_count')");
if (!$ok) { echo "Mysql Error: ".mysql_error(); }
flush();
}
}
}
?>
You can have cron jobs run once a minute.
To do this follow these steps:
Make a script that runs your PHP code, for example:
#!/bin/bash
wget myurl.com/blah > /dev/null
Save it as my-cron.sh in some folder (like /var)
Add it to cron. Run crontab -e See Cron Format and Crontab usage.
This for example, will run it once a minute.
# Minute Hour Day of Month Month Day of Week Command
* * * * * /var/my-cron.sh
If I get well your need, the best thing for you is to use cron job making a script run indefinitely will not be a good idea.
As specifier in one of you comments you are using a hosting server Godaddy so probably you will not be able to have shell access, BUT depending on your cPanel version you may be able to create and define cron job.
see this link and this google search
Perhaps, if you don't have this option and you are wiling to let a browser opened I would suggest the following
create an html page as a client which would make an ajax request every hours to your PHP script, like this you emulate a cron job function
the ajax request code might look like (using jQuery)
function makeRequest(){
$.ajax({
url: "http://yourhost/url-to-your-script.php",
complete: function(data){
setTimeout(function(){
makeRequest();
}, 60 * 60 * 1000); // Minutes * Seconds * MS
}
});
}
makeRequest();
I hope this helps
EDIT
this link might help too
IMPORTANT DO NOT FORGET TO REMOVE THE INFINITE LOOP
I just had same issue.
Only cron job can do if you want run script off browser. You can set up cron job with free providers or you can set up cron job in windows's Scheduled tasks.
If your site has a good traffic then you can follow the option below that your users does the work for you.
In php you can find time in hour and seconds
$time= date(' H:i:s');
create a table to track if the code was run.
eg; table column name check with option 0 and 1;
select check from table.
enter code here
if ($minute > 59)
{
if($check==0)
{
run your code
then update the table each time when it was run
eg; update table set check='1'
}
}
then another if condition to reset your code
if(minute>0 && minute <1)
{
select check from your table.
if(check==1)
{
update table set check='0'
}
}

How to run a code after a specified time?

I have a big problem:
A user logs in, and the session opens.
After that he clicks a button (in a form) which action is "example.php".
This example.php should increase one record in MySQL database by 1.
How to write this "example.php"?
Please help.
EDIT:
Sorry, I haven't asked what i was supposed to ask.
Main problem:
After a user clicks a button, the example.php script should execute after a specified time, for example, a 600 sec.
The other problem is that the user can click the button and log out, and despite that, the example.php should execute 600 sec later.
EDIT (18:48):
OK, I've read all your suggestions, but dont't have an idea how to make all of this things work together.
I made a form.php, with input type="submit" and action="example.php".
I want to:
1. start a javascript timer;
2. increase a value in database after a time, specified earlier in a variable.
Please, if it is possible, give me an example, how to do this.
In example.php execute SQL:
UPDATE table SET field = field + 1;
Do you need more info to do that ?
EDIT:
I think that there is no other way like jobs mechanism. When user calls example.php, you add to the database new job with a current timestamp + 600 seconds.
Parallel there should be running some job executor that will gather from database all jobs that have timestamp set to timestamp <= NOW().
If it will some records, call specified piece of code and remove/mark as done that jobs.
You may delay the execution of code using sleep
Example:
<?php
echo 'Script Start: '.date('h:i:s') . '<br>';
sleep(5); // delay in seconds (here 5)
echo 'Script Ende: '.date('h:i:s') . '<br>';
?>
I do not know if what you are trying to do makes perfect sense, but your exampl.php would look something like:
<?php
sleep(600); // delay in seconds
// the code to be executed delayed here
?>
There are several ways you could go about doing this...
As mentioned there is the sleep method.
You could have a job - i.e. Add something to a jobs list and have a cronjob check it every so often to see if it is due.
You could use a javascript timer to execute after x number of seconds.
<?php
if( isset($_POST['submit_button']) ) {
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$sql = 'UPDATE table SET counter_column = counter_column + 1'; // WHERE table_name_id =' . intval($id);
mysql_query($sql, $link);
}
?>
This example.php will only update the value if the submit_button is clicked on and not if you just type in the URL example.php

Categories