Jump to content

Inserting multiple records at once from a HTML form - PHP MYSQL


Smitch

Recommended Posts

Hey,

I have a html form that a user can enter the details of $i number of friends. Ive setup the form to generate enough fields according to how many friends they want to enter. Once they submit the form the contents is posted to a php script where I want to insert each persons details as a new record.

 

The name of the fields look like:

Name1

Email1

Name2

Email2

 

How can I create a loop to insert each persons details into a new record?

-----------------------------------------------

So far I have come up with the following PHP code. That doesnt work. The INSERT INTO line is where the issues are.

 

<?php

$con = mysql_connect("localhost","paulandp_sand","sand");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

mysql_select_db("paulandp_sand", $con);

 

$amnt = $_GET['txtamnt'];

 

while ($i <= $amnt)

      {

      $sql="INSERT INTO testpay (Firstname, Lastname, company, phone, email)      VALUES ('$_POST['firstname,$i']','$_POST[lastname,'$i']','$_POST[company,'$i']','$_POST[phone,'$i']','$_POST[email,'$i']')";

     

      if (!mysql_query($sql,$con))

        {

        die('Error: ' . mysql_error());

        }

      echo "1 record added";

      }

     

mysql_close($con)

?>

 

Any suggestions would be much appreciated.

 

Thanks,

SM17CH

When you say "doesn't work", what do you mean? And you may want to consider a multi-VALUE()'ed insert as well (and using code blocks when you post).

 

ok,

to narrow the question down a little more:

 

each form field now looks like this:

"firstname1","email1"

"firstname2","email2"

"firstname3","email3" etc...

 

in the PHP script I have an INSERT INTO statement inside a loop where I grab the form data using $_POST[fieldname]

 

The problem I am having is I don't know how to combine $_POST[fieldname] with the variable $i which contains a number to create the field name.

 

At the moment my Insert Into statement looks like:

$sql="INSERT INTO database (firstname) VALUES ('$_post['firstname".$i."']')";

 

But returns:Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

 

Thanks again.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.