str_replace variables to send email? Code not working...

Discussion in 'PHP' started by bigtime, Sep 2, 2011.

  1. #1
    If I enter the following on the form:

    {user} is username

    This is the output I get:

    John Smith is username

    John Smith is username

    John Smith is username

    John Smith is username

    Obviously it should be a different name for each line. Here is my code:

    	$sql = "SELECT email, name, username, id FROM review_users";
    
        $result = mysql_query($sql) or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));
    
    while ($row = mysql_fetch_array($result)) { 
    	$username = stripslashes($row["username"]);
    
    $msg = str_replace("{user}", $row["username"], $msg);
    
    echo "$msg<br /><br />";
    }
    PHP:
    Any ideas on why the str_replace is throwing off my expected results?

    Thanks in advance,

    Tim
     
    Solved! View solution.
    bigtime, Sep 2, 2011 IP
  2. #2
    Inside the loop, change $msg to something else so that it would not be overwritten ( {user} is being killed on the first loop and does not exist on the rest ).

    $sql = "SELECT email, name, username, id FROM review_users";
    
        $result = mysql_query($sql) or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));
    
    while ($row = mysql_fetch_array($result)) {
        $username = stripslashes($row["username"]);
    
    $message = str_replace("{user}", $row["username"], $msg);
    
    echo "$message<br /><br />";
    }
    PHP:
     
    iBank ™, Sep 2, 2011 IP
    bigtime likes this.
  3. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you so much! Can't believe how much hair I pulled out over something so simple!!!!!

    Tim
     
    bigtime, Sep 2, 2011 IP
  4. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #4
    Did you mean $msg = str_replace("{user}", $row["username"], $username)?

    Exactly which string do you want to find the string '{user}' in? $row['username']? (Which you already have in $username, with the slashes removed.)

    BTW, since you're not using $msg for anything else, why even create it? Just echo the result of str_replace:

    echo str_replace(needle, replacement, haystack);

    (And no need for the double quotes - it just gives the server more work.)
     
    Rukbat, Sep 2, 2011 IP
  5. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks guys. So how would I make it work with multiple replacements?

    while ($row = mysql_fetch_array ($result)) {
         $msg = str_replace('{username}', $row['username'], $msg);
         $msg = str_replace('{id}', $row['id'], $msg);
         $msg = str_replace('{name}', $row['name'], $msg);
         $msg = str_replace('{email}', $row['email'], $msg);
    }
    
    echo "$msg";
    PHP:
    Thanks,

    Tim
     
    bigtime, Sep 8, 2011 IP
  6. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #6
    
    
    [COLOR=#000088]$search = array('{username}', '{id}', '{name}', '{email}');
    $replace = array('$row['username'], [/COLOR][COLOR=#000088]'$row['id'],[/COLOR][COLOR=#000088]'$row['name'],[/COLOR][COLOR=#000088]'$row['email']);[/COLOR]  
    
    [COLOR=#000088]$msg[/COLOR] [COLOR=#339933]=[/COLOR] str_replace[COLOR=#009900]([/COLOR][COLOR=#0000ff]$search[/COLOR][COLOR=#339933],[/COLOR] [COLOR=#000088]$replace[/COLOR][COLOR=#339933],[/COLOR] [COLOR=#000088]$msg[/COLOR][COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]
    
    
    Code (markup):
     
    Rukbat, Sep 8, 2011 IP
  7. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thanks for the replies. It still sends the same $msg to everyone in the list which contains the data for the first user selected. Here is my output which shows it is looping and I do get an email to each email address in the database:

    Message sent to :gmail (d@gmail.com)
    Message sent to :Timothy (webmaster@df.com)
    Message sent to :tim2 (as@df.net)
    Message sent to :tim (tim@df.net)


    Here is my complete script:


    <?php
    // Grab our config settings
    require_once($_SERVER['DOCUMENT_ROOT'].'/PHPMailer/class.phpmailer.php');
    // instantiate the class
    $mail = new PHPMailer();
    
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->Host       = 'localhost'; // SMTP server
    $mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                               // 1 = errors and messages
                                               // 2 = messages only
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->SMTPKeepAlive = true;                  // SMTP connection will not close after each email sent
    $mail->Host       = 'localhost'; // sets the SMTP server
    $mail->Port       = 25;                    // set the SMTP port for the Gmailer server
    $mail->Username   = 'user'; // SMTP account username
    $mail->Password   = 'pass!!';        // SMTP account password
    
    include ("../body.php");
    include ("../functions.php");
    include ("../f_secure.php");
    include ("../config.php");
     
    $mail->AddReplyTo('sales@d.com','d.com');
    $mail->SetFrom('sales@d.com','d.com');
    
    $subject = clean($_POST['subject']);
    $mail->Subject    = "$subject";
    $msg = clean($_POST['msg']);
    
     
    // Setup body
    $msg = 'Hello {username},
    
    Here is your info:
    
    id - {id}
    name - {name}
    email - {email}';
     
    // Get the user's Email
    $sql  = 'SELECT email, name, username, id FROM review_users_test';
    $result = mysql_query($sql);
     
    while ($row = mysql_fetch_array ($result)) {
        // Send the emails in this loop.
    
    $search = array('{username}', '{id}', '{name}', '{email}');
    $replace = array($row['username'], $row['id'],$row['name'],$row['email']);  
    
    $msg = str_replace($search, $replace, $msg);
    
    $mail->AddAddress($row['email'], $row['name']);
    $mail->Body = "$msg";
    $mail->isHTML(false);
    
      if(!$mail->Send()) {
        echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
      } else {
        echo "Message sent to :" . $row["name"] . ' (' . str_replace("@", "&#64;", $row["email"]) . ')<br />';
      }
      // Clear all addresses and attachments for next loop
      $mail->ClearAddresses();
      $mail->ClearAttachments();
      }
     
    ?>
    PHP:
    I'm getting close to a working product if I could just figure out how to parse the message ($msg).

    Thanks,

    Tim
     
    bigtime, Sep 9, 2011 IP
  8. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Finally solved! Thanks everyone for the help. Here's the working code:

    // Setup body
    $message = "Hello {username},
    
    Here is your info:
    
    id - {id}
    name - {name}
    email - {email}";
     
    // Get the user's Email
    $sql  = 'SELECT email, name, username, id FROM review_users_test';
    $result = mysql_query($sql);
     
    while ($row = mysql_fetch_array ($result)) {
        // Send the emails in this loop.
    $msg = "$message";
    
    $search = array('{username}', '{id}', '{name}', '{email}');
    $replace = array($row['username'], $row['id'],$row['name'],$row['email']);  
    
    $msg = str_replace($search, $replace, $msg);
    
    $mail->AddAddress($row['email'], $row['name']);
    $mail->Body = stripslashes($msg);
    $mail->isHTML(false);
    
      if(!$mail->Send()) {
        echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
      } else {
        echo "Message sent to :" . $row["name"] . ' (' . str_replace("@", "&#64;", $row["email"]) . ') - '."$msg".'<br />';
      }
     
      // Clear all addresses and attachments for next loop
      $mail->ClearAddresses();
     // $mail->ClearAttachments();
      }
    PHP:
     
    bigtime, Sep 10, 2011 IP
  9. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #9
    Elegant code, but brute force would have been easier to write. Something like:

    
    
    // Get the user's Email
    $sql  = 'SELECT email, name, username, id FROM review_users_test';
    $result = mysql_query($sql);
     
    while ($row = mysql_fetch_array ($result)) {
        // Send the emails in this loop.
    $message = "Hello $row['username'],
    
    Here is your info:
    
    id - $row['id'] 
    name - $row['name']
    email - $row['email']"; 
    
    PHP:
     
    Rukbat, Sep 10, 2011 IP
  10. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #10
    When this goes live, $message will be coming from a $_POST. I believe that will limit me to the method I used??

    Thanks,

    Tim
     
    bigtime, Sep 10, 2011 IP
  11. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #11
    No.
    
    // Get the user's Email
    $sql  = 'SELECT email, name, username, id FROM review_users_test';
    $result = mysql_query($sql);
     
    while ($row = mysql_fetch_array ($result)) {
        // Send the emails in this loop.
    $message = "$_POST['greeting'] $row['username'],
    
    $_POST['first_line'
    
    $_POST['id'] $row['id'] 
    $_POST['name'] $row['name']
    $_POST['email'] $row['email']";
    
    PHP:
     
    Rukbat, Sep 10, 2011 IP
  12. hotnoob

    hotnoob Member

    Messages:
    96
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    28
    #12
    don't listen to rukbat, he is more clueless than you are.
     
    hotnoob, Sep 11, 2011 IP