Search code examples
phpdatabaseeventsschedulingreminders

Given an event with date and time, how to send an email 2 days before the event?


Exactly what the title says.

In my database, I have a list of users and a list of events with date and time.

How do I write the script which enables me to automatically (preferrably) send an email to the users list reminding them about the event 2 days earlier?

EDIT: I was thinking of using this but I'm not sure how to implement it exactly.


Solution

  • Is this a database question?

    Depending on your table structure.. something like this might work for you

    SELECT * FROM user
    INNER JOIN event ON user.id = event.user_id
    WHERE DATE(event.event_datetime) = DATE(DATE_ADD(NOW(), INTERVAL 2 DAY));
    

    This would select all events where the event_datetime is two days from now.

    EDIT:

    Here's a quick and dirty, untested script that may work for you

    <?php
    
    //change these to whatever your database settings are
    $host = 'localhost';
    $dbname = 'my_database';
    $user = 'username';
    $password = 'password';
    
    //create a new PDO handle
    $dbh = new PDO("mssql:host=$host;dbname=$dbname", $user, $password);
    
    //prepare your query
    $sth = $dbh->prepare("SELECT * FROM user
    INNER JOIN event ON user.id = event.user_id
    WHERE DATE(event.event_datetime) = DATE(DATE_ADD(NOW(), INTERVAL 2 DAY))");
    
    //execute query and fetch results
    $sth->execute();
    $results = $sth->fetchAll();
    
    //iterate through results and send event notification emails
    foreach($results as $result) {
        //send event notification emails using your queried results eg. result['email'], $result['event_datetime'], $result['event_info'] ...
    }
    
    ?>