Sagar
Sagar

Reputation: 9

How to keep running a query to check database all the time every minute in PHP and JavaScript

I am making a project which is a website. Basically it will set a reminder and notify the user using email/SMS. I am using PHP and JavaScript. My database stores the the list of users in table 1 and a separate table for each user and his tasks(with the time and dates). I want to refer the database every minute to check for tasks even if the user is not logged in(browser is closed). What do i do to keep running the check for query all the time? I want something that will run in background all the time even if user never opens the browser. Please help. The php code to store in a users database is

<?php
include("init.php");
session_start();
if(isset($_POST))
{
    $date = $_POST["date"];
    $event = $_POST["event"];
    $time = $_POST["time"];
    $daily = $_POST["daily"];
    $weekly = $_POST["weekly"];
    $monthly  = $_POST["monthly"];
    $fname = $_SESSION['fname'];
    $fname = mysql_real_escape_string($fname);
    $sql = "insert into $fname(fname,date,event,time,daily,weekly,monthly) values('$fname','$date','$event','$time','$daily','$weekly','$monthly')";

    if(mysqli_multi_query($con,$sql))
        echo "<br><h3> row inserted...</h3>done";
    else
        echo "Error in insertion...".mysqli_error($con);
}
?>

There is no issue with the code. I just need to know how and using what can i refer the database all the time at the server end when user is not on the page. Can php work 24hrs even if the browser is closed because i know javascript wont work.

Upvotes: 0

Views: 822

Answers (2)

abhishekdgeek
abhishekdgeek

Reputation: 41

Sagar what you are looking for is CRON Task. I am afraid that PHP and Javascript alone can't trigger it.

Work flow:

  1. Make an API containing all your business logic or processing you need to execute it.
  2. Register a CRON job in cPanel or crontab -e in your linux machine.
  3. Use the end point directly using AJAX calls or make a separate end point as cron task will continue working.

Refer to this link in case you want to learn more about cron jobs - http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples

Thanks, Abhishek Jain

Upvotes: 0

You need to create an event in MySQL (or the database manager you are using, for example:

CREATE EVENT e_totals
->     ON SCHEDULE AT '2006-02-10 23:59:00'
->     DO INSERT INTO test.totals VALUES (NOW());

Or a recurrent event:

delimiter |

CREATE EVENT e_daily
    ON SCHEDULE
      EVERY 1 DAY
    COMMENT 'Saves total number of sessions then clears the table each day'
    DO
      BEGIN
        INSERT INTO site_activity.totals (time, total)
          SELECT CURRENT_TIMESTAMP, COUNT(*)
            FROM site_activity.sessions;
        DELETE FROM site_activity.sessions;
      END |

delimiter ;

Upvotes: 1

Related Questions