Search code examples
phphtmlemailunsubscribe

How to generate unsubscribe link in email?


I have a newsletter system so when I want to send a message to all of my subscribers I send it trough a php file named post-processing.php.

Here is my post-processing.php code:

$count=$dbo->prepare("select * from sw_post where post_id=:post_id");
$count->bindParam(":post_id",$post_id,PDO::PARAM_INT,4);

if($count->execute()){
   echo " Success <br>";
   $row = $count->fetch(PDO::FETCH_OBJ);
   $sub=$row->sub;
   $post=$row->post;
} else {
   echo "Database Error ..";
print_r($count->errorInfo()); 

exit;
}
/////////////////////////

$dtl="";

$dtl .=$post. "\n\n";


@$headers.="Reply-to: $from_email\n"; 
$headers .= "From: $from_email\n"; 
$headers .= "Errors-to: $from_email\n"; 
//$headers = "Content-Type: text/html; charset=iso-8859-1\n".$headers;
// Above line is required to send HTML email 
$sql="select email_id, email from sw_email where status='A'"; 
$i=0;

foreach ($dbo->query($sql) as $row) {
   $url=$base_url."unsubscribe.php?email_id=$row[email_id]&email=$row[email]&todo=delete";
   $dtl .= "Click on the URL to unsubscribe  $url ";

Let's say I have three subscribers, and when I receive the email I get this outcome:

Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=1&[email protected]&todo=delete
Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=2&[email protected]&todo=delete
Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=3&[email protected]&todo=delete

But the outcome I want is only:

Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=1&[email protected]&todo=delete

I don't want the recipent to recive the links to unsubscribe to all of my subscribers. How do I fix this?


Solution

  • Bind your email code inside of foreach after getting user lists

      @$headers.="Reply-to: $from_email\n"; 
      $headers .= "From: $from_email\n"; 
      $headers .= "Errors-to: $from_email\n"; 
    //$headers = "Content-Type: text/html; charset=iso-8859-1\n".$headers;
    $sql="select email_id, email from sw_email where status='A'"; 
    foreach ($dbo->query($sql) as $row) {
        $dtl =$post. "\n\n";    
    
        $url=$base_url."unsubscribe.php?email_id=$row[email_id]&email=$row[email]&todo=delete";
        $dtl .= "Click on the URL to unsubscribe  $url ";
    
        mail('to_email','subject',$dtl,$headers); //this is your mail function
    }