Explode query

Solved
Hello,

From a table with two columns (Mail and ColonneAExploder). The rows for Mail contain email addresses and the ColonneAExploder field contains text like "word1, word2, word3".

I’m looking, with a variable ($var) for example containing the text "word2", to send an email (using phpMailer) to the addresses that have "word2" in the records of ColonneAExploder.

[Code snippet with PHP pseudocode is provided, attempting to explode ColonneAExploder values and then select emails where the exploded value equals $var, and send to those addresses.]

Is this the right method?

Thanks,
Daniel

2 answers

  1. It is then necessary to treat $mailAdresse as an array with a foreach.
    0
    1. Moderator
      Hello!
      This is Bobot, the forum AI!
      Your approach is almost correct, but you have a few errors in your code. Here is a correction:

      First, when using the `explode` function, it would be better to use it inside a `foreach` loop to check each element of the "ColonneAExploder" column separately. Then, instead of using `$valeur= :var` in the prepared statement, you should use the `LIKE` clause.

      Here is a corrected version of your code :

      ```PHP
      $req1 = $bdd->prepare("SELECT Mail, ColonneAExploder FROM Table");
      $req1->execute();
      $resultat = $req1->fetchAll();

      if (!empty($resultat)){
      foreach ($resultat as $champs){
      $valeurs = explode(", ", $champs['ColonneAExploder']);
      if (in_array($var, $valeurs)){
      $req2 = $bdd->prepare("SELECT mail FROM Table WHERE ColonneAExploder LIKE :var");
      $req2->bindValue(':var', '%'.$var.'%');
      $req2->execute();
      $result = $req2->fetchAll();
      if (!empty($result)){
      foreach ($result as $mailAdresse){
      // Send an email with phpMailer using $mailAdresse['mail'] as the recipient
      }
      }
      }
      }
      }
      ```

      In this code, I use the `in_array` function to check if the variable `$var` is found in the array `$valeurs`, which is the result of the `explode` operation. If so, I perform another query to obtain the email addresses associated with the value of `$var`. I then use these addresses to send emails with phpMailer.

      0