MySQL
  Home arrow MySQL arrow Page 8 - Date Arithmetic With MySQL
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Date Arithmetic With MySQL
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 35
    2003-07-03


    Table of Contents:
  • Date Arithmetic With MySQL
  • When Two And Two Don't Make Four
  • Counting Down
  • The Number Game
  • Artificial Intelligence
  • A Short Interval
  • Lather, Rinse, Repeat
  • Code Poet

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Date Arithmetic With MySQL - Code Poet
    ( Page 8 of 8 )

    Now that the table structure is defined and some sample data has been stored in it, all that's needed is a script to parse the data and execute the appropriate tasks (based on the scheduled date of each task). Here's an example of what this script might look like:


    <?php

    // define array to convert interval type
    // to corresponding SQL clause for DATE_ADD()
    $typeArray = array("D" => "DAY", "M" => "MONTH", "Y" => "YEAR");

    // what is today?
    $today = date("Y-m-d", mktime());

    // open connection to database
    $connection = mysql_connect("localhost", "root", "secret") or die ("Unable to connect!");
    mysql_select_db("db1") or die ("Unable to select database!");

    // formulate and execute query
    // get a list of all tasks due today
    $query = "SELECT `id`,`msg`,`type`,`interval`,`date`, `owner` FROM `tasks` WHERE `date` = CURRENT_DATE()"; $result = mysql_query($query) or die("Error in query: " . mysql_error());

    // iterate over result set
    while ($row = mysql_fetch_object($result))
    {
    // for each task:

    // send email
    mail($row->owner, "[REMINDER] $today" , $row->msg) or die("Unable to send
    mail!");

    // calculate next run date for task and update tale
    $query2 = "UPDATE tasks SET `date` = DATE_ADD(`date`, INTERVAL `interval` " . $typeArray[$row->type] . " ) WHERE id = '" . $row->id . "'";
    $result2 = mysql_query($query2) or die("Error in query: " . mysql_error()); }

    // close connection
    mysql_close($connection);

    ?>

    Now, I've written this script in PHP; however, once you understand how it works, it should be fairly easy to write an equivalent piece of code in Perl, Python, Bash or any other language. This script should be executed once a day (maybe via a cron job - note that you will need to compile a PHP binary in order to use the script above as is); it will scan the records in the table, perform date calculations, and send out notifications to the email address specified for each task if it turns out that the task is due on that particular day.

    The first thing the script does is figure out the current date (and format it to a MySQL-compliant format). Next, it executes an SQL query in order to obtain a list of all the tasks to be executed on the current date, and sends email notification to the owner of each task. The DATE_ADD() function discussed previously is then used to calculate the next run date of the task (by adding the specified interval period to the current date) and the table is updated appropriately with new dates.

    Of course, this is not a foolproof design. Missing even a single script run could well result in some tasks not being executed and consequently, their next run dates not being updated. If these are recurring tasks, then future invocations of the script will not "see" them, and they will never be executed again.

    This design flaw may be worked around by intermittently running automated scripts to verify the integrity of the table. Redundant tasks, or tasks with dates outside a specific temporal window, can be sent to a system administrator for inspection and deletion where needed.

    Thus, by allowing you to perform arithmetic operations on temporal data, MySQL's date/time API allows you to easily and accurately build applications to manipulate date and time values. The example above is just one of many possibilities this opens up - I'll leave the rest to your imagination. Go on, think about it - and if you come up with something interesting, write in and tell me about it.

    Until then, though...stay healthy!

    Note: Examples in this article have been tested on Linux/i586 with MySQL 4.0 and PHP 4.2.3. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!



     
     
    >>> More MySQL Articles          >>> More By icarus, (c) Melonfire
     

       

    MYSQL ARTICLES

    - MySQL Security Tips
    - Designing a MySQL Database: Tips and Techniq...
    - The Three Most Important MySQL Queries
    - Null and Empty Strings
    - MySQL Server Tuning Tips and Tricks
    - MySQL Query Optimizations and Schema Design
    - MySQL Benchmarking Tools and Utilities
    - MySQL Benchmarking Concepts and Strategies
    - Take Some Load off MySQL with MemCached
    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT