Jump to content

inserting into multiple tables


crag

Recommended Posts

Hi. I am a newbie to php mysql and I hope you can help me with this small problem.

I have 2 tables one named bandname with ID, bandname and contactID
a 2nd table named contactinfo with ID, name, tel, email.

The data for inserting into the tables is taken from a form.

->I firstly insert the contactinfo data into its table
->then i assign the bandname ID to a variable (contactid) using mysql_insert_id()
->then i insert the bandname and contactid into bandname table.

My problem is this:
When I submit the form data my code inserts the first record fine but when I try to submit a second record it
inserts 3 records. 1 record that is fine and another two that are a mix of the two correct records.

if(isset($_POST['name'])) {
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$sql1 = "INSERT INTO contactinfo SET
name = '$name',
tel = '$tel',
email = '$email'";
if(isset($_POST['bandname'])) {
$bandname = $_POST['bandname'];
$contactid = mysql_insert_id();
$sql2 = "INSERT INTO bandname SET
bandname = '$bandname',
contactid = '$contactid'";
if((@mysql_query($sql1) && (@mysql_query($sql2)) {
echo '<p>The contact info has been added to the database</p>';
} else {
echo '<p>Error submitting contact info: ' . mysql_error() . '</p>';
}
}
}

Can anyone please tell me what is wrong here

sorry I didn't use a code tag.
[code]
if(isset($_POST['name'])) {
                        $name = $_POST['name'];
                        $tel = $_POST['tel'];
                        $email = $_POST['email'];
                        $sql1 = "INSERT INTO contactinfo SET
                            name = '$name',
                            tel = '$tel',
                            email = '$email'";
                        if(isset($_POST['bandname'])) {
                            $bandname = $_POST['bandname'];
                            $contactid = mysql_insert_id();
                            $sql2 = "INSERT INTO bandname SET
                                bandname = '$bandname',
                                contactid = '$contactid'";
                            if((@mysql_query($sql1) && (@mysql_query($sql2)) {
                                echo '<p>The band name has been added to the database</p>';
                            } else {
                                echo '<p>Error submitting band name: ' . mysql_error() . '</p>';
                            }
                        }
                    }
[/code]
Link to comment
https://forums.phpfreaks.com/topic/4522-inserting-into-multiple-tables/
Share on other sites

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.