Search code examples
phpemailwhile-looparray-push

Get some records from a while loop to an array, then send these records in an email


I have a while loop:

$users = mysqli_query($con, "SELECT * FROM table");
while($row = mysqli_fetch_array($users)) {          
  if    ($row['column1'] !=  $row['column2']) {
    echo "There is a different between column1 and column2<br />";
  }
}

I want to get all the records where column1 is different from column2 and get these values into an email.

The email looks like this:

ID     Column1   Column2
1      111       222
4      222       333

I thought I could do this with array_push but I'm not getting it to work.

Any idea how to get this done?


Solution

  • As you want to send an HTML table by email, you just have to create an HTML table and add some lines each time you have an error. Then include it into your email's content and send the mail.

    $users = mysqli_query($con, "SELECT * FROM table");
    
    // Table header
    $htmlError = '<table><tr><th>ID</th><th>Column 1</th><th>Column 2</th></tr>';
    
    while($row = mysqli_fetch_array($users)) {
    
        if  ($row['column1'] !=  $row['column2']) {
            // Add new row to table
            $htmlError .= '<tr><td>'.$row['id'].'</td><td>'.$row['column1'].'</td><td>'.$row['column2'].'</td></tr>';
        }
    }
    
    // End table
    $htmlError .= '</table>';
    
    // Send mail
    ...