Hi there,
I would like to make an email form that would select all the emails from a MySQL db and then send that message to all addresses.

I got this script but was unable to get it working. Any help would be great.

<?php 
//Connect to database
 
	mysql_connect("localhost","user","password") or die(mysql_error());
	mysql_select_db("db") or die(mysql_error());

$sql = "SELECT email FROM members";
	$res = mysql_query($sql) or die(mysql_error());
	while( $row = mysql_fetch_assoc($res) )
	{
	 $area = $row['email']. ", ";  
			
	// read the list of emails from the file.
	$email_list = $area;
	
	// count how many emails there are.
	$total_emails = count($email_list);
	
	// go through the list and trim off the newline character.
	for ($counter=0; $counter<$total_emails; $counter++) {
   $email_list[$counter] = trim($email_list[$counter]);
   }
 
	$to = $email_list;
 
	echo $to;
	}

if (isset($_REQUEST['email']))
//if "email" is filled out, send email
	  {
	  //send email
	  
	  $email = $_REQUEST['email'] ; 
	  
	  $subject = $_REQUEST['subject'] ;
	  $message = $_REQUEST['message'] ;
	  mail( "someone@example.com", "Subject: $subject",
	  $message, "From: $email" );
	  echo "Thank you for using our mail form";
	  }
	else
	//if "email" is not filled out, display the form
	  {
	  echo "<form method='post' action='mailform.php'>
	  Subject: <input name='subject' type='text' /><br />
	  Message:<br />
	  <textarea name='message' rows='15' cols='40'>
	  </textarea><br />
	  <input type='submit' />
	  </form>";
	  }
?>

Above file is mailform.php and of course i have changed db connection etc.
Thanks in advance

Recommended Answers

All 14 Replies

Hi there,
I would like to make an email form that would select all the emails from a MySQL db and then send that message to all addresses.

I got this script but was unable to get it working. Any help would be great.

<?php 
//Connect to database
 
	mysql_connect("localhost","user","password") or die(mysql_error());
	mysql_select_db("db") or die(mysql_error());

$sql = "SELECT email FROM members";
	$res = mysql_query($sql) or die(mysql_error());
	while( $row = mysql_fetch_assoc($res) )
	{
	 $area = $row['email']. ", ";  
			
	// read the list of emails from the file.
	$email_list = $area;
	
	// count how many emails there are.
	$total_emails = count($email_list);
	
	// go through the list and trim off the newline character.
	for ($counter=0; $counter<$total_emails; $counter++) {
   $email_list[$counter] = trim($email_list[$counter]);
   }
 
	$to = $email_list;
 
	echo $to;
	}

if (isset($_REQUEST['email']))
//if "email" is filled out, send email
	  {
	  //send email
	  
	  $email = $_REQUEST['email'] ; 
	  
	  $subject = $_REQUEST['subject'] ;
	  $message = $_REQUEST['message'] ;
	  mail( "someone@example.com", "Subject: $subject",
	  $message, "From: $email" );
	  echo "Thank you for using our mail form";
	  }
	else
	//if "email" is not filled out, display the form
	  {
	  echo "<form method='post' action='mailform.php'>
	  Subject: <input name='subject' type='text' /><br />
	  Message:<br />
	  <textarea name='message' rows='15' cols='40'>
	  </textarea><br />
	  <input type='submit' />
	  </form>";
	  }
?>

Above file is mailform.php and of course i have changed db connection etc.
Thanks in advance

some part of your code needs little bit of mending , like -

//Connect to database
	mysql_connect("localhost","user","password") or die(mysql_error());
	mysql_select_db("db") or die(mysql_error());
	$sql = "SELECT email FROM members";
	$res = mysql_query($sql) or die(mysql_error());
	
	while($row = mysql_fetch_assoc($res) )
	{
		 $area .= $row['email']. ", ";  
				
	}
// read the list of emails from the file.
	$email_list = explode(',', $area);
	
	// count how many emails there are.
	$total_emails = count($email_list);
	
	// go through the list and trim off the newline character.
	for ($counter=0; $counter<$total_emails; $counter++)
	{
		$email_list[$counter] = trim($email_list[$counter]);
	}
 
	$to = $email_list;
 
	echo $to;

Cold anyone schow me how to get 1 email from mysql and send the mail to that emailaddress? Currently i got this code, but ´not working:

//CONNECT TO MYSQL
$link=mysql_connect($mysqladd, $mysqluser, $mysqlpass) or die('Could not connect to database: ' . mysql_error());

//CONNECT TO DATABASE
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

$query="SELECT * FROM jobadd"; 
 
$result=mysql_query($query); 
 
$num=mysql_numrows($result); 
 

 
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
  if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5($_POST['captcha_code']) == $_SESSION['random_txt']) { 
    unset($_POST['captcha_code'],$_SESSION['random_txt']); 
  } 
  else { if ($errorpage == 'false') {
    echo '<b>Fel kod!</b><br>'; 
    echo '<a href="javascript:history.back()">Försök igen!</a>'; 
    exit; 
  } if ($errorpage == 'true')  { 
    header('Location: ././error.php'); 
  exit; 
  } 
}
}  
?>
<?php

   function ValidateEmail($email)
   {
      $pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i';
      return preg_match($pattern, $email);
   }

   if($_SERVER['REQUEST_METHOD'] == 'POST')
   {
      $mailto = '<?php echo mysql_result($result,"Epost"); ?>';
      $mailfrom = isset($_POST['email']) ? $_POST['email'] : $mailto;
      $subject = 'Svar på Tjänstförfrågan från Jobler.se';
      $message = 'Hej, Vi vill gärna lämna en facktura på denna Tjänstförfrågan';
      $success_url = './tack.php';
      $error_url = './error.php';
      $error = '';
      $eol = "\n";
      $max_filesize = isset($_POST['filesize']) ? $_POST['filesize'] * 1024 : 1024000;
      $boundary = md5(uniqid(time()));

      $header  = 'From: '.$mailfrom.$eol;
      $header .= 'Reply-To: '.$mailfrom.$eol;
      $header .= 'MIME-Version: 1.0'.$eol;
      $header .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"'.$eol;
      $header .= 'X-Mailer: PHP v'.phpversion().$eol;
      if (!ValidateEmail($mailfrom))
      {
         $error .= "The specified email address is invalid!\n<br>";
      }

      if (!empty($error))
      {
         $errorcode = file_get_contents($error_url);
         $replace = "##error##";
         $errorcode = str_replace($replace, $error, $errorcode);
         echo $errorcode;
         exit;
      }

      $internalfields = array ("submit", "reset", "send", "captcha_code");
      $message .= $eol;
      $message .= $_SERVER['REMOTE_ADDR'];
      $message .= $eol;
      foreach ($_POST as $key => $value)
      {
         if (!in_array(strtolower($key), $internalfields))
         {
            if (!is_array($value))
            {
               $message .= ucwords(str_replace("_", " ", $key)) . " : " . $value . $eol;
            }
            else
            {
               $message .= ucwords(str_replace("_", " ", $key)) . " : " . implode(",", $value) . $eol;
            }
         }
      }

      $body  = 'This is a multi-part message in MIME format.'.$eol.$eol;
      $body .= '--'.$boundary.$eol;
      $body .= 'Content-Type: text/plain; charset=ISO-8859-1'.$eol;
      $body .= 'Content-Transfer-Encoding: 8bit'.$eol;
      $body .= $eol.stripslashes($message).$eol;
      if (!empty($_FILES))
      {
          foreach ($_FILES as $key => $value)
          {
             if ($_FILES[$key]['error'] == 0 && $_FILES[$key]['size'] <= $max_filesize)
             {
                $body .= '--'.$boundary.$eol;
                $body .= 'Content-Type: '.$_FILES[$key]['type'].'; name='.$_FILES[$key]['name'].$eol;
                $body .= 'Content-Transfer-Encoding: base64'.$eol;
                $body .= 'Content-Disposition: attachment; filename='.$_FILES[$key]['name'].$eol;
                $body .= $eol.chunk_split(base64_encode(file_get_contents($_FILES[$key]['tmp_name']))).$eol;
             }
         }
      }
      $body .= '--'.$boundary.'--'.$eol;
      mail($mailto, $subject, $body, $header);
      header('Location: '.$success_url);
      mysql_close();
      exit;
   }

?>

Epost is the column name that all the mails are stored in

I'v taken out the db connection part.

Before you jump in one's script you must know what is happening. Try understanding how PHP Mail works. then it will make your task easier

Still dont get it, Sorry

Still dont get it, Sorry

what you don't get?

how to get 1 email from mysql and send the mail to that emailaddress?

Yes i got this, but my code does not work.

Yes i got this, but my code does not work.

which code? I cannot peep in your computer and see your code. You have to post your RELEVANT current code!

commented: Peep into your computer! Love it :) +14

DB CONNECT CODE:

<?php

$databasename='****'; // Name of the database
$tablename='****'; // Name of the table
$mysqladd='****'; // Address to the MySQL Server
$mysqluser='****'; // Your MySQL UserName
$mysqlpass='****'; // Your MySQL Password


//CONNECT TO MYSQL
$link=mysql_connect($mysqladd, $mysqluser, $mysqlpass) or die('Could not connect to database: ' . mysql_error());

//CONNECT TO DATABASE
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());


$query="SELECT * FROM jobadd"; 
 
$result=mysql_query($query); 
 
$num=mysql_numrows($result); 
 
mysql_close(); 
 
 
$i=0; 
while ($i < $num) : 
?>

EMAIL FUNCTION CODE:

<?php
function ValidateEmail($email)
   {
      $pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i';
      return preg_match($pattern, $email);
   }

   if($_SERVER['REQUEST_METHOD'] == 'POST')
   {
      $mailto = '<?php echo mysql_result($result,$i,"Epost"); ?>';
      $mailfrom = isset($_POST['email']) ? $_POST['email'] : $mailto;
      $subject = 'Svar på Tjänstförfrågan från Jobler.se';
      $message = 'Hej, Vi vill gärna lämna en facktura på denna Tjänstförfrågan';
      $success_url = './tack.php';
      $error_url = './error.php';
      $error = '';
      $eol = "\n";
      $max_filesize = isset($_POST['filesize']) ? $_POST['filesize'] * 1024 : 1024000;
      $boundary = md5(uniqid(time()));

      $header  = 'From: '.$mailfrom.$eol;
      $header .= 'Reply-To: '.$mailfrom.$eol;
      $header .= 'MIME-Version: 1.0'.$eol;
      $header .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"'.$eol;
      $header .= 'X-Mailer: PHP v'.phpversion().$eol;
      if (!ValidateEmail($mailfrom))
      {
         $error .= "The specified email address is invalid!\n<br>";
      }

      if (!empty($error))
      {
         $errorcode = file_get_contents($error_url);
         $replace = "##error##";
         $errorcode = str_replace($replace, $error, $errorcode);
         echo $errorcode;
         exit;
      }

      $internalfields = array ("submit", "reset", "send", "captcha_code");
      $message .= $eol;
      $message .= $_SERVER['REMOTE_ADDR'];
      $message .= $eol;
      foreach ($_POST as $key => $value)
      {
         if (!in_array(strtolower($key), $internalfields))
         {
            if (!is_array($value))
            {
               $message .= ucwords(str_replace("_", " ", $key)) . " : " . $value . $eol;
            }
            else
            {
               $message .= ucwords(str_replace("_", " ", $key)) . " : " . implode(",", $value) . $eol;
            }
         }
      }

      $body  = 'This is a multi-part message in MIME format.'.$eol.$eol;
      $body .= '--'.$boundary.$eol;
      $body .= 'Content-Type: text/plain; charset=ISO-8859-1'.$eol;
      $body .= 'Content-Transfer-Encoding: 8bit'.$eol;
      $body .= $eol.stripslashes($message).$eol;
      if (!empty($_FILES))
      {
          foreach ($_FILES as $key => $value)
          {
             if ($_FILES[$key]['error'] == 0 && $_FILES[$key]['size'] <= $max_filesize)
             {
                $body .= '--'.$boundary.$eol;
                $body .= 'Content-Type: '.$_FILES[$key]['type'].'; name='.$_FILES[$key]['name'].$eol;
                $body .= 'Content-Transfer-Encoding: base64'.$eol;
                $body .= 'Content-Disposition: attachment; filename='.$_FILES[$key]['name'].$eol;
                $body .= $eol.chunk_split(base64_encode(file_get_contents($_FILES[$key]['tmp_name']))).$eol;
             }
         }
      }
      $body .= '--'.$boundary.'--'.$eol;
      mail($mailto, $subject, $body, $header);
      header('Location: '.$success_url);
      exit;
   }


?>
Member Avatar for diafol

What happened to the end of the db code?
Anyway this:

$mailto = '<?php echo mysql_result($result,$i,"Epost"); ?>';

is wrong. What are you trying to do?

I'm trying to get an email address from db. I'v fixt it now.

$mailto = ''.$_POST['mailto'].'';

Anoter problem i have

//CONNECT TO MYSQL
$link=mysql_connect($mysqladd, $mysqluser, $mysqlpass) or die('Could not connect to database: ' . mysql_error());

//CONNECT TO DATABASE
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

$query="SELECT * FROM jobadd ORDER BY Timestamp DESC LIMIT 0, 10"; 

if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
  //we give the value of the starting row to 0 because nothing was found in URL
  $startrow = 0;
//otherwise we take the value from the URL
} else {
  $startrow = (int)$_GET['startrow'];
}
$query="SELECT * FROM jobadd ORDER BY Timestamp DESC LIMIT $startrow, 10";
echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.($startrow+10).'">Nästa&nbsp;&nbsp;&nbsp;&nbsp;</a>';
$prev = $startrow - 10;

//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
    echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.$prev.'">Föregående</a>';

 
$result=mysql_query($query); 
 
$num=mysql_numrows($result); 

mysql_close(); 
 
 
$i=0; 
while ($i < $num) : 
?>

I'v got Text links "Nästa" "Föregående" to move throw pages but i also want numbers, e.g, if i have 55 posts and 10 posts per page thats 6 pages, i want between "Nästa" and "Föregående" linked numbers 1 2 3 4 5 6. Any idees?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.