MrVaux Posted April 13, 2011 Share Posted April 13, 2011 Im petty new to php, so if you choose to help me please explain it like I was 5 What I am trying to do is this (short version) I have af form from which I can mail users from my DB. This form has a dropdown for which users I want to email. Lets say: All Group2+3 Group1 Group2 Group3 When hitting Submit you are taken to "send.php" As for now I have this: <?php include "config.php"; $link = mysql_connect($dbhost, $dbuser, $dbpasswd) or die("Couldn't establish connection"); mysql_select_db($dbname); $gruppe = $_REQUEST['gruppe']; // Running the MySQL query if($_REQUEST['password'] == "something") { $results = mysql_query("SELECT * FROM medlemmer WHERE tilknytning = '$gruppe'"); //$results = mysql_query("SELECT * FROM medlemmer"); // Pulling up the results and iterating through them while ($row = mysql_fetch_object($results)) { // Emailing each member $ToEmail = $row->email; $EmailSubject = "BGA Nyhedsbrev"; $mailheader = "From: BGA\n"; $mailheader .= "Reply-To: noreply@bga.dk\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = " <H2>BGA Nyhedsbrev</H2><br>"; $MESSAGE_BODY .= "".nl2br($_POST["mailtekst"])."<br>"; mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); } mysql_query($query) or die("Nyhedsbrev udsendt med succes!<br><br><a href='nyhedsbrev.php'>Tilbage</a>"); } if ($query) { echo "Nyhedsbrev udsendt med succes!<br><br>"; echo "<a href='nyhedsbrev.php'>Tilbage</a>"; } else { echo "Password ikke udfyldt eller opgivet forkert !!!"; } ?> This is ONLY woking for individual groups, when I want to email 2 or more groups I dont know what to do? I think I have to use arrays but I am not sure at all. Can someone help me here? Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 13, 2011 Share Posted April 13, 2011 Either change the select list to a multi-select list or use checkboxes for each group you want to be able to select. In either case you will name the field (or fields) as an array, i.e. name="fieldName[]" Quote Link to comment Share on other sites More sharing options...
MrVaux Posted April 14, 2011 Author Share Posted April 14, 2011 Still can´t get it to work I did the checkboxes but it only works when I only select one of the checkboxes? FORM: echo " <p>\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"BGA\" />BGA<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"BGA spiller\" />BGA spillere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"BGA træner\" />BGA trænere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"GFK\" />GFK<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"GFK spiller\" />GFK spillere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"GFK træner\" />GFK trænere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"AIF\" />AIF<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"AIF spiller\" />AIF spillere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"AIF træner\" />AIF trænere<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"Futsal\" />Futsal<br />\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"Ledelse\" />Ledelse\n"; echo " <input type=\"checkbox\" name=\"mailtarget[]\" value=\"Andre\" />Andre\n"; echo " </p>\n"; SEND.PHP <?php include "config.php"; $link = mysql_connect($dbhost, $dbuser, $dbpasswd) or die("Couldn't establish connection"); mysql_select_db($dbname); $gruppe = $_REQUEST['mailtarget']; $N = count($gruppe); for($i=0; $i < $N; $i++) //$gruppe = $_REQUEST['bga']; // Running the MySQL query if($_REQUEST['password'] == "bgabga") { $results = mysql_query("SELECT * FROM medlemmer WHERE tilknytning = '$gruppe'"); //$results = mysql_query("SELECT * FROM medlemmer"); // Pulling up the results and iterating through them while ($row = mysql_fetch_object($results)) { // Emailing each member $ToEmail = $row->email; $EmailSubject = "BGA Nyhedsbrev"; $mailheader = "From: BGA\n"; $mailheader .= "Reply-To: noreply@bga.dk\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = " <H2>BGA Nyhedsbrev</H2><br>"; $MESSAGE_BODY .= "".nl2br($_POST["mailtekst"])."<br>"; mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); } mysql_query($query) or die("Nyhedsbrev udsendt med succes!<br><br><a href='mail.html'>Tilbage</a>"); } if ($query) { echo "Nyhedsbrev udsendt med succes!<br><br>"; echo "<a href='mail.html'>Tilbage</a>"; echo "$bga"; } else { echo "Password ikke udfyldt eller opgivet forkert !!!"; } ?> What am I missing here? Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 14, 2011 Share Posted April 14, 2011 The first thing is you need to redo the logic for pulling the records. You should NEVER run queries in loops there is almost always a way to run a single query instead of multiple and when there isn't you are probably trying to do something you shouldn't be. Second, you need to add debugging code so you can actually see what data is being returned so you know where the problem is. Also, don't use $_REQUEST, use $_POST or $_GET instead. Looking at your code I think the problem is that you have a for loop, but the code to run within that loop isn't enclosed in brackets {}, so the loop really isn't running. But, no matter you don't want to do it that way anyway. Your checkbox fields look fine, so try this for the processing page. I don't understand the purpose of all your code because of the language, but I think I understand it enough. <?php //Check if password is correct if($_POST['password'] != "bgabga") { //Password does not match echo "Password ikke udfyldt eller opgivet forkert !!!"; } elseif(!isset($_POST['mailtarget']) || count($_POST['mailtarget'])<1) { //No records were selected echo "Please select one or more recipients"; } else { //Now that we know we are going to do a query we can connect to the DB include "config.php"; $link = mysql_connect($dbhost, $dbuser, $dbpasswd) or die("Couldn't establish connection"); mysql_select_db($dbname); //Clean the user input $gruppeArry = array_map('mysql_real_escape_string', $_POST['mailtarget']); $gruppeList = "'" . implode("', '", $gruppeArry) . "'"; //Create and run query $query = "SELECT email, tilknytning FROM medlemmer WHERE tilknytning IN ($gruppeList)", $result = mysql_query($query) or die("Query:<br>$query<br>Error:<br>".mysql_error()); //Check if there were results if(mysql_num_rows($result)<1) { echo "There were no matching records"; } else { //Define these BEFORE the loop since they are static $EmailSubject = "BGA Nyhedsbrev"; $mailheader = "From: BGA\n"; $mailheader .= "Reply-To: noreply@bga.dk\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = " <H2>BGA Nyhedsbrev</H2><br>"; $MESSAGE_BODY .= "".nl2br($_POST["mailtekst"])."<br>"; //Get recipient email address and send email $success = array(); $errors = array(); while ($row = mysql_fetch_object($results)) { $ToEmail = $row->email; $sent = mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); if($sent) { $success[] = $row->tilknytning; } else { $errors[] = $row->tilknytning; } } //Output success/error messages if(count($success)>0) { echo "Emails were successfully sent to the following users:<br>\n"; echo "<ul>\n"; foreach($success as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } if(count($errors)>0) { echo "There were problems sending emails to the following users:<br>\n"; echo "<ul>\n"; foreach($errors as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } echo "<br><br><a href='mail.html'>Tilbage</a>{$bga}"; } } ?> Quote Link to comment Share on other sites More sharing options...
MrVaux Posted April 14, 2011 Author Share Posted April 14, 2011 mjdamato! You are my GOD Cleaned it for a few typing errors and it worked like a charm. Now I just need to take the time to study it so I can actually understand it. I really appreciate the time and effort you put into this, can´t really thank you enough. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 14, 2011 Share Posted April 14, 2011 The only thing I think I used that you were not already using was the IN statement for the query. Basically it checks for any values in the specified field that match any of the values IN the list. Other than that, I think the code I used should be pretty strait forward. The main thing I did was rearrange the logic to be more elegant. I think it is always better on if/else statements to have the error conditions come first - but that's just my preference. I also added some logic to catch individual errors on the emails. It might be overkill for your needs, but it only takes a few minutes to add something like that and it will save a ton of time later if there are any problems. Quote Link to comment Share on other sites More sharing options...
MrVaux Posted May 13, 2011 Author Share Posted May 13, 2011 So I am back with this with a new struggle. The script is actually for sending out newsletters to all the members of a football club. The script below works fine for now. Added something here and there ex. the opportunity to unsubscribe to the newsletter. The table in the MySQL callled "medlemmer" is storing all the data including the members email and his moms and dads emails. 3 rows: email mom_email dad_email I want the script to send out emails to mom and dad to when the checkbox "parents" is checked but I have no idear how to do this. The query goes like this: $query = "SELECT email, tilknytning, nyhedsbrev FROM medlemmer WHERE tilknytning IN ($gruppeList) && nyhedsbrev = 'Ja'"; Do i have to add mom_email, dad_email to this. Already tried that with no luck. Any help would be appriciated. <?php //Check if password is correct if($_POST['password'] != "secret") { //Password does not match echo "Password ikke udfyldt eller opgivet forkert !!!"; } elseif(!isset($_POST['mailtarget']) || count($_POST['mailtarget'])<1) { //No records were selected echo "Vælg venligst mindst én modtagergruppe"; } else { //Now that we know we are going to do a query we can connect to the DB include "config.php"; $link = mysql_connect($dbhost, $dbuser, $dbpasswd) or die("Couldn't establish connection"); mysql_select_db($dbname); //Clean the user input $gruppeArry = array_map('mysql_real_escape_string', $_POST['mailtarget']); $gruppeList = "'" . implode("', '", $gruppeArry) . "'"; //Create and run query $query = "SELECT email, tilknytning, nyhedsbrev FROM medlemmer WHERE tilknytning IN ($gruppeList) && nyhedsbrev = 'Ja'"; $result = mysql_query($query) or die("Query:<br>$query<br>Error:<br>".mysql_error()); //Check if there were results if(mysql_num_rows($result)<1) { echo "Der blev ikke fundet nogen modtagere i den valgte gruppe"; } else { //Define these BEFORE the loop since they are static $EmailSubject = "BGA Nyhedsbrev"; $mailheader = "From: BGA\n"; $mailheader .= "Reply-To: noreply@bga.dk\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY .= "<table width='738px' style='border-width:1px; border-style:solid; border-color:#999999;' cellspacing'0' cellpadding'0' bgcolor='#EEEEEE' align='center'>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td width='738px' align='center'><img src='http://www.bga.dk/medlemmer/newsletter/images/banner.jpg' border='1'></td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td width='100%' align='left'><H2>BGA Nyhedsbrev</H2></td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td>\n"; $MESSAGE_BODY .= "".nl2br($_POST["mailtekst"]).""; $MESSAGE_BODY .= " </td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= "</table>\n"; //Get recipient email address and send email $success = array(); $errors = array(); while ($row = mysql_fetch_object($result)) { $ToEmail = $row->email; $sent = mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); if($sent) { $success[] = $row->tilknytning; } else { $errors[] = $row->tilknytning; } } //Output success/error messages if(count($success)>0) { echo "Nyhedsbrevet udsendt til følgende grupper:<br>\n"; echo "<ul>\n"; foreach($success as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } if(count($errors)>0) { echo "Der opstod et problem med at sende ud til følgende gruppe:<br>\n"; echo "<ul>\n"; foreach($errors as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } echo "<br><br><a href='nyhedsbrev.html'>Udsend flere nyhedsbreve</a> - <a href='..\medlemmer.php'>Tilbage til medlemsliste</a>{$bga}"; } } ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 13, 2011 Share Posted May 13, 2011 The query goes like this: $query = "SELECT email, tilknytning, nyhedsbrev FROM medlemmer WHERE tilknytning IN ($gruppeList) && nyhedsbrev = 'Ja'"; Do i have to add mom_email, dad_email to this. Already tried that with no luck. Only if you want to use that data - so the answer is yes. But, just adding additional fields to a query isn't going to do anything with that data unless you code for it. You will also need to pull the value for the "parents" checkbox. You don't say what that field is called. So, your query would look something like this: $query = "SELECT email, tilknytning, nyhedsbrev, mom_email, dad_email, parentsCheckbox FROM medlemmer WHERE tilknytning IN ($gruppeList) && nyhedsbrev = 'Ja'"; Next, modify your code for defining the recipients for each email. I will assume that if the email is going to the parents that it is OK to send one email to the three recipients if($row->parentsCheckbox!=1) { //Parents checkbox NOT selected $ToEmail = $row->email; } else { //Parents checkbox selected $ToEmail = "{$row->email}; {$row->mom_email}; {$row->dad_email}"; } Quote Link to comment Share on other sites More sharing options...
MrVaux Posted May 13, 2011 Author Share Posted May 13, 2011 I actually did try something like this, but when you are not sure of which symbol to use I get stuck ( or { or , I think this is going the right way but perhaps I didn´t explain myself enough. The checkboxes: (foraldre = parents) <input type="checkbox" name="mailtarget[]" value="BGA">BGA<br> <input type="checkbox" name="mailtarget[]" value="BGA spiller">BGA spillere<br> <input type="checkbox" name="mailtarget[]" value="BGA traner">BGA trænere<br> <input type="checkbox" name="mailtarget[]" value="GFK">GFK<br> <input type="checkbox" name="mailtarget[]" value="GFK spiller">GFK spillere<br> <input type="checkbox" name="mailtarget[]" value="GFK traner">GFK trænere<br> <input type="checkbox" name="mailtarget[]" value="AIF">AIF<br> <input type="checkbox" name="mailtarget[]" value="AIF spiller">AIF spillere<br> <input type="checkbox" name="mailtarget[]" value="AIF traner">AIF trænere<br> <input type="checkbox" name="mailtarget[]" value="Futsal">Futsal<br> <input type="checkbox" name="mailtarget[]" value="Andre">Andre<br> <input type="checkbox" name="mailtarget[]" value="Foraldre">Forældre<br><br> The MySQL table: -- -- Table structure for table `medlemmer` -- CREATE TABLE `medlemmer` ( `id` int(11) NOT NULL auto_increment, `fornavn` varchar(25) NOT NULL default '', `efternavn` varchar(50) NOT NULL default '', `adresse` varchar(50) NOT NULL default '', `postnr` varchar(25) NOT NULL default '', `bynavn` varchar(25) NOT NULL default '', `telefon` varchar(25) NOT NULL default '', `mobil` varchar(25) NOT NULL default '', `mor_mobil` varchar(25) NOT NULL default '', `far_mobil` varchar(25) NOT NULL default '', `email` varchar(50) NOT NULL default '', `mor_email` varchar(50) NOT NULL default '', `far_email` varchar(50) NOT NULL default '', `foedselsdato` varchar(25) NOT NULL default '', `aargang` varchar(25) NOT NULL default '', `hold` varchar(50) NOT NULL default '', `traeners_navn` varchar(25) NOT NULL default '', `aargangsleders_navn` varchar(50) NOT NULL default '', `tidligere_klubber` varchar(100) NOT NULL default '', `startet_til_fodbold` varchar(25) NOT NULL default '', `albertslund_medlem` varchar(25) NOT NULL default '', `glostrup_medlem` varchar(25) NOT NULL default '', `udvalgt_til_talenttrup` varchar(25) NOT NULL default '', `cheftraener` varchar(25) NOT NULL default '', `medlemsnr` varchar(25) NOT NULL default '', `tilknytning` varchar(50) NOT NULL default '', `indmeldt` varchar(25) NOT NULL default '', `udmeldt` varchar(25) NOT NULL default '', `billede` blob NOT NULL, `nyhedsbrev` varchar(25) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; As you can see there is no table for parents, but one called mor_email and one called far_email. So basicly I want to mail mum and dad too for the groups chosen when I select the foraldre (parents) checkbox. So if i want to mail the group BGA I want the parents to get the mail too when I also select the checkbox "foraldre" Does it make any sense at all? Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 13, 2011 Share Posted May 13, 2011 OK, if I understand you correctly, the option to select parents is not an option associated with the records in the `medlemmer` table. instead it is an option when submitting the form to send the emails. So, the logic is still the same, just check the POST value in the logic I provided instead of the database value. Although I don't understand your checkbox array. If you are using the checkboxes to select the recipients, then what is the purpose of the query to get recipients? Oh well. if(in_array('Foraldre', $_POST['mailtarget'])) { //Parents checkbox NOT selected $ToEmail = $row->email; } else { //Parents checkbox selected $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; } Quote Link to comment Share on other sites More sharing options...
MrVaux Posted May 14, 2011 Author Share Posted May 14, 2011 if(in_array('Foraldre', $_POST['mailtarget'])) { //Parents checkbox NOT selected $ToEmail = $row->email; } else { //Parents checkbox selected $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; } Ok, now i tried the above code but can´t really get it to work :'( I tried diffent things: The latest I only changed the: $ToEmail = $row->email; to $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; This meaning there is no check whatsoever if the parents checkbox is checked or not. If I understand this correctly, this should just send out mails to all parents in the choosen fields But I get an error page displaying nothing but "Failure" ? Are you sure of this?: $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; Quote Link to comment Share on other sites More sharing options...
MrVaux Posted May 23, 2011 Author Share Posted May 23, 2011 I was really hoping some sort of help here. I googled the solution you provided but didn´t find anything of use. Below is the full script (send.php) with the latest modification. But it generates an error. Browser just comes out with "Failure" Im pretty sure this is the line that makes tho error. //Parents checkbox selected $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; mjdamato where are you Your knowledge is needed... <?php //Check if password is correct if($_POST['password'] != "yipiyaa") { //Password does not match echo "Password ikke udfyldt eller opgivet forkert !!!"; } elseif(!isset($_POST['mailtarget']) || count($_POST['mailtarget'])<1) { //No records were selected echo "Vælg venligst mindst én modtagergruppe"; } else { //Now that we know we are going to do a query we can connect to the DB include "config.php"; $link = mysql_connect($dbhost, $dbuser, $dbpasswd) or die("Couldn't establish connection"); mysql_select_db($dbname); //Clean the user input $gruppeArry = array_map('mysql_real_escape_string', $_POST['mailtarget']); $gruppeList = "'" . implode("', '", $gruppeArry) . "'"; //Create and run query $query = "SELECT email, mor_email, far_email, tilknytning, nyhedsbrev FROM medlemmer WHERE tilknytning IN ($gruppeList) && nyhedsbrev = 'Ja'"; $result = mysql_query($query) or die("Query:<br>$query<br>Error:<br>".mysql_error()); //Check if there were results if(mysql_num_rows($result)<1) { echo "Der blev ikke fundet nogen modtagere i den valgte gruppe"; } else { //Define these BEFORE the loop since they are static $EmailSubject = "Nyhedsbrev"; $mailheader = "From: BGA Fodbold <noreply@bga.dk>\r\n"; $mailheader .= "Reply-To: noreply@bga.dk\r\n"; $headers = "MIME-Version: 1.0\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY .= "<table width='738px' style='border-width:1px; border-style:solid; border-color:#999999;' cellspacing'0' cellpadding'0' bgcolor='#EEEEEE' align='center'>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td width='738px' align='center'><img src='http://www.bga.dk/medlemmer/newsletter/images/banner.jpg' border='1'></td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td width='100%' align='left'><H2>BGA Nyhedsbrev</H2></td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= " <tr>\n"; $MESSAGE_BODY .= " <td>\n"; $MESSAGE_BODY .= "".nl2br($_POST["mailtekst"]).""; $MESSAGE_BODY .= " </td>\n"; $MESSAGE_BODY .= " </tr>\n"; $MESSAGE_BODY .= "</table>\n"; //Get recipient email address and send email $success = array(); $errors = array(); while ($row = mysql_fetch_object($result)) { //Parents checkbox NOT selected if(in_array('Foraldre', $_POST['mailtarget'])) { $ToEmail = $row->email; } else { //Parents checkbox selected $ToEmail = "{$row->email}; {$row->mor_email}; {$row->far_email}"; } $sent = mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); if($sent) { $success[] = $row->tilknytning; } else { $errors[] = $row->tilknytning; } } //Output success/error messages if(count($success)>0) { echo "Nyhedsbrevet udsendt til følgende grupper:<br>\n"; echo "<ul>\n"; foreach($success as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } if(count($errors)>0) { echo "Der opstod et problem med at sende ud til følgende gruppe:<br>\n"; echo "<ul>\n"; foreach($errors as $username) { echo "<li>{$username}</li>\n"; } echo "<ul>\n"; } echo "<br><br><a href='nyhedsbrev.html'>Udsend flere nyhedsbreve</a> - <a href='..\medlemmer.php'>Tilbage til medlemsliste</a>{$bga}"; } } ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 23, 2011 Share Posted May 23, 2011 Use commas instead of semi-colons to delimit the multiple recipients in the $ToEmail string. FYI: If you are having problems where a process is failing due to the data being used, you should echo the data to the page to validate what you have. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.