Include in the email only the dates that are about to end

Asked

Viewed 48 times

0

I’m preparing an email to send, but I just want to include in it the dates that are to end within X days.

At present I have so:

while ($row = mysql_fetch_array($validade)) {
  $id = $row[0];
  $Nome = $row[1];
  $AlvaraValidade = $row[2];
  $AcidenteValidade = $row[3];
  $SeguroValidade = $row[4];
  $FinancasValidade = $row[5];
  $SocialValidade = $row[6];
  $RemuneracaoValidade = $row[7];
  $InstaladorValidade = $row[8];
  $MontadorValidade = $row[9];
  $MedicaValidade = $row[10];
  $ProjectistaValidade = $row[11];
  $GasValidade = $row[12];
  $RedesValidade = $row[13];
  $SoldadorValidade = $row[14];
  $MecanicoValidade = $row[15];
  $ClasSoldadorValidade = $row[16];
  $MaquinaValidade1 = $row[17];
  $MaquinaValidade2 = $row[18]; 
  $MaquinaValidade3 = $row[19]; 
  $MaquinaTopoValidade = $row[20];

  // ...
}

And then in the body of Email I show all fields:

$PHPMailer->Body = "
<body>
  <p>
    <strong>Faltam 10 dias para terminar um ou mais documentos do </strong> $Nome
</body>
<body>
  <p><strong>As datas sao:</strong>
</body>

Question

How can I check if the date of a given field is to end within X days to include it in the email?

  • I edited your question to better explain the problem. When asking a question, don’t assume that whoever answers it is aware of your other questions. Try to clarify the problem in isolation to enable the question and get answers :)

1 answer

4


To mention the fields whose date is about to end, you must compare the date with a deadline, in order to determine whether the field should be present in the email. Let’s assume that the deadline is 10 days for clarity in the answer.

Compare dates

The simplest way is to convert to Unix timestamp the date contained in the field and the current date+10days (deadline) using the function strtotime() while we do the checking:

//                         teu campo menor 
//                       que daqui a 10 dias
//                                ↑
//                                │
//        converter a data        │   converter a data de
//       do teu campo da BD       │    hoje mais 10 dias
//   ┌────────────┴────────────┐ ┌┴┐ ┌─────────┴─────────┐
if ( strtotime($row["teuCampo"])  <  strtotime("+10 days") ) {
  // fazer algo porque tem menos de 10 dias
}

From the example above, you can perform various types of comparisons to determine if your date is as you intended.

As long as you have the code running inside the if(xx){ /* código aqui*/ } you’re already creating the limitation you want.

Applying to your case

In your code, you have several fields that appear to be dates, for each one you want to check you should proceed by using the example below:

Comparison

Let’s compare and create the text for the email only if the date is to end in the next 10 days:

while ($row = mysql_fetch_array($validade)) {

  // inicio do teu código

  /* COMPARAR */
  // iniciar variável a vazio
  $AlvaraValidadeHTML = '';

  // verificar se o valor de $row[2] é menor que daqui a 10 dias
  if ( strtotime($row[2])  <  strtotime("+10 days") ) {
    $AlvaraValidadeHTML = '<p>A validade do Alvará vai terminar no dia: '.$row[2].'</p>';
  }

  // resto do teu código
}

Attach to email body

We build the email body the way we want and apply the variables that contain the message for each document in the desired location.

If they contain a value resulting from the comparison made, they will appear, if not, they are empty and it is as if they were not there:

$PHPMailer->Body = "
<body>
  <p>
    <strong>
      Faltam 10 dias para terminar um ou mais documentos do $Nome
    </strong> 
  </p>
  ".$AlvaraValidadeHTML."
  ".$AcidenteValidadeHTML."
  ".$SeguroValidadeHTML."
</body>";

Note: The formatting of the HTML for the email you have in question is incorrect, you should have only one tag body.


Optimisation

If you’re actually going to do a lot of comparison of expiration dates, it’s best to create a function to avoid repeating code over and over again:

/**
 * Está para expirar ?
 * 
 * Verifica se determinada data vai expirar até ao número de dias fornecido.
 * 
 * @param string $data      A data a verificar
 * @param integer $dias     Número de dias no futuro
 * 
 * @return $boolean         Verdadeiro ou falso
 */
function estaParaExpirar($data, $dias) {
    return ( strtotime($data)  <  strtotime("+".$dias." days") );
}

while ($row = mysql_fetch_array($validade)) {

    $id = $row[0];
    $Nome = $row[1];

    // se está para expirar dentro de 10 dias, recebe o texto, caso não fica vazio.
    $AlvaraValidade = estaParaExpirar($row[2], "10") ? '<p>A data do alvará vai expirar no dia '.$row[2].'</p>' : '';
    $AcidenteValidade = estaParaExpirar($row[3], "10") ? '<p>A data do acidente vai expirar no dia '.$row[3].'</p>' : '';
    $SeguroValidade = estaParaExpirar($row[4], "10") ? '<p>A data do seguro vai expirar no dia '.$row[4].'</p>' : '';
    // ... e continua nos restantes campos...

    // no corpo email é a mesma coisa que já te apresentei em cima.

Note: The function is very simple, created to facilitate things in this particular case, it always expects to receive a date in the first parameter and a number (days) in the second parameter. To use the function in other scenarios, it should confirm if the date is actually a date and not "junk" and if the number of days is even a number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.