Martin
Martin

Reputation: 63

How do i email data from a form built with a while loop?

As part of a project I have a form in which our clients can edit a list of the keywords in which we work on as part of their SEO.

This is the code I use to display the keywords we have for them on our database

<?php
$c = true;
while($row = mysql_fetch_array($result))
{
  $counter++;
  echo "<div" .(($c = !$c)?' class="right"':'') . ">";
  echo "<label for='keyword". $counter ."'>",
       "<strong>Keyword " . $counter . " </strong></label>";
  echo "<input type='text' name='keyword". $counter .
       "' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
  echo "</div>";
}
?>

What I don't know what do do is collect the data when the form is submitted into an email. I have the PHP mail bit ready but struggling on this a bit.

Any help?

Upvotes: 1

Views: 135

Answers (4)

SW4
SW4

Reputation: 71240

I'd recommend changing the code to this:

<?php
$c = true;
while($row = mysql_fetch_array($result))
{
  $counter++;
  echo "<div" .(($c = !$c)?' class="right"':'') . ">";
  echo "<label for='keyword". $counter ."'>",
       "<strong>Keyword " . $counter . " </strong></label>";
  echo "<input type='text' name='keyword[]' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
  echo "</div>";
}
?>

You can then access all keywords in the target php file for your form (after submission) using $_POST['keyword'], eg

foreach($_POST['keyword'] as $key => $value) {
      echo "Keyword #". $key." value: ". $value."<br />";
      // or your code to build your message
}

Upvotes: 1

stecb
stecb

Reputation: 14766

Brian and Ergo summary are right, but if you don't want to modify the code inside the while loop you could, at the end of that, insert an hidden input that holds the last $counter value. Then in the target php file (where you will send the email), you can load the POST fields (modifying what Stephen wrote):

<?php
$counter = (int)$_POST['counter'];
$message = '';
for($i = 1; $i <= $counter; $i++){
    $key = $_POST['keyword'.$i];
    $message .= "<p>";
    $message .= "<strong>Keyword " . $key . " </strong></label>";
    $message .= "<span> " . $post . "</span>";
    $message .= "</p>";
}

// mail message here.
?>

Upvotes: 0

Stephen
Stephen

Reputation: 18984

To use the POST data (make sure your form is using POST):

<?php
    $message = '<ol>';
    foreach($_POST as $key => $post) {
        $message .= "<li><strong>Keyword " . $key . ":</strong>";
        $message .= " <span>" . $post . "</span>";
        $message .= "</li>";
    }
    $message .= '</ol>';

    // mail the message here.
?>

Upvotes: 0

Brian
Brian

Reputation: 15706

Instead of naming the inputs like "keyword1", "keyword2", etc, just name them all "keyword[]". When the form is submitted, PHP will aggregate them all into an array.

Upvotes: 0

Related Questions