简体   繁体   中英

How do I add data from a form with a variable number of rows into a MySQL table?

I have a form in two sections on a webpage. Each section contains a variable number of rows (the user can add more rows). I have a PHP page which processes the form as an email, but I am now looking to extend this so that information is added to a My SQL database that I have in place. Below is the code for the form and the php processing page as it stands.

I have started to include the code for submitting the data to the MySQL table at the bottom of the PHP page, but I am not sure how to do this, given that there are a variable number of rows in two sections, and would be grateful for any help in getting this working.

Here is the HTML for the form:

<form method="post" name="booking" action="bookingengine.php">
    <fieldset>
        <h2>Waged/Organisation Rate</h2>
        <p>
            <input type="text" name="name[]">
            <input type="text" name="email[]">
            <input type="text" name="organisation[]">
            <input type="text" name="position[]">
        </p>
        <p><span class="add">Add person</span></p>
    </fieldset>

    <fieldset>
        <h2>Unwaged Rate</h2>
        <p>
            <input type="text" name="name2[]">
            <input type="text" name="email2[]">
        </p>
        <p><span class="add">Add person</span></p>
    </fieldset>

    <p><input type="submit" name="submit" id="submit" value="Submit and proceed to payment page" class="submit-button" /></p>

</form>

And here is the booking engine.php:

<? include 'connection.php'; ?>

<?php

$emailFrom = "****";
$emailTo = "****";
$subject = "Booking for Soteria Conference";

$body = "The following people have booked for the Soteria Conference in Derby:" . "\n\n" . "Waged/Organisation Rate:" . "\n\n";
$row_count = count($_POST['name']);
$row_count2 = count($_POST['name2']);



for($i = 0; $i < $row_count; $i++)
{
  // variable sanitation...
  $name = trim(stripslashes($_POST['name'][$i]));
  $email = trim(stripslashes($_POST['email'][$i]));
  $organisation = trim(stripslashes($_POST['organisation'][$i]));
  $position = trim(stripslashes($_POST['position'][$i]));

  // this assumes name, email, and telephone are required & present in each element
  // otherwise you will have spurious line breaks. 
  $body .= "Name: " . $name . "    Email: " . $email . "  Organisation: " . $organisation . "   Position: " . $position . "\n\n";
}

$body .= "Unwaged Rate:" . "\n\n";

for($j = 0; $j < $row_count2; $j++)
{
  // variable sanitation...
  $name2 = trim(stripslashes($_POST['name2'][$j]));
  $email2 = trim(stripslashes($_POST['email2'][$j]));

  // this assumes name, email, and telephone are required & present in each element
  // otherwise you will have spurious line breaks. 
  $body .= "Name: " . $name2 . "    Email: " . $email2 . "\n\n";
}

// send email 
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=payment.html\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}

?>

Here is the structure of connection.php:

<?php

$hostname = "localhost";
$database = "****";
$username = "****";
$password = "****";

$conn = mysql_connect($hostname, $username, $password) or die ('Error connecting to mysql');
mysql_select_db($database);

?>

I'm not sure what you mean. But your HTML code should be more like this :

<p>
  <input type="text" name="persons[][name]">
  <input type="text" name="persons[][email]">
  <input type="text" name="persons[][organisation]">
  <input type="text" name="persons[][position]">
</p>

And then at the end of your PHP script

$values = array();
foreach ($_POST['persons'] as $person) {
    // Sanitize your datas
    ...
    // SQL VALUES TO INSERT
    $values[] = '(' . $person['name'] . ',' . $person['email'] . ',' . $person['organisation'] . ',' . $person['position'] . ')';
}
$query = "INSERT INTO person (name, email, organization, position) VALUES " . implode(',', $values);

The same logic applies for Unwaged rates

edit if you want to keep your HTML

 $values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name'][$i]));
     $email = trim(stripslashes($_POST['email'][$i]));
     $organisation = trim(stripslashes($_POST['organisation'][$i]));
     $position = trim(stripslashes($_POST['position'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks. 
     $body .= "Name: " . $name . "    Email: " . $email . "  Organisation: " . $organisation . "   Position: " . $position . "\n\n";

     //prepare the values for MySQL
     $values[] = '(' . $name . ',' . $email . ',' . $organisation . ',' . $position . ')';
}
$query = "INSERT INTO person (name, email, organization, position) VALUES " . implode(',', $values);

 And for unwaged rate

 $values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name'][$i]));
     $email = trim(stripslashes($_POST['email'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks. 
     $body .= "Name: " . $name . "    Email: " . $email . "\n\n";

     //prepare the values for MySQL
     $values[] = '(' . $name . ',' . $email . ')';
}
$query = "INSERT INTO person (name, email) VALUES " . implode(',', $values);

If you need multiple inputs, I recommend using multidimensional arrays (which you're currently doing - but not effectively):

<fieldset id="1">
   <legend>Row 1</legend>
   <input type="text" name="name[1]"/>
   <input type="text" name="email[1]"/>
   <input type="text" name="address[1]"/>
</fieldset>
<fieldset id="2">
   <legend>Row 2</legend>
   <input type="text" name="name[2]"/>
   <input type="text" name="email[2]"/>
   <input type="text" name="address[2]"/>
</fieldset>

You can use JavaScript (like jQuery) to append more rows (if they click on a button for example). You can use the fieldset ID to populate the array key for the new row. Here's the PHP I'd use:

foreach ($_POST['name'] as $row_number => $value){
   $query = 'INSERT INTO table (name' . $row_number . ', user_id) VALUES (' . $value . ', ' . $user_id . ')';  
}

If you're expecting lots of rows, you can set up a table that lists each name as a separate row (with a user_id column) rather than as a column in a table that lists rows per user. So instead of doing:

user_id | name1 | name2 | name 3

1 | James | John | Jimbob
2 | Sandy | Samm | Sandra

You can do:

id | order | user_id | value

1 | 1 | 1 | James
2 | 2 | 1 | John
3 | 3 | 1 | Jimbob
4 | 1 | 2 | Sandy
5 | 2 | 2 | Samm
6 | 3 | 2 | Sandra

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM