Click to See Complete Forum and Search --> : How to insert data into tables related by foreign keys


xtopher23
01-14-2009, 06:03 AM
Hi everybody! Well I'm building a web app using php which is connected to a MySQL database (I don't have much experience in web development). My db has some tables related by foreign keys and the problem I'm actually having is that when I try to collect data from a form and insert them in these tables, I get the following error:

"Cannot add or update a child row: a foreign key constraint fails (`tradelink/client`, CONSTRAINT `client_ibfk_1` FOREIGN KEY (`acc_id`) REFERENCES `account` (`acc_id`) ON UPDATE CASCADE)"

Here's part of my code:
...
$sql_1="INSERT INTO client (f_name, l_name, tel) VALUES ('$Fname', '$Lname', '$Phone')";

$result_1 = mysql_query($sql_1);
if (!$result_1)
{
die('Sorry, could not query the database! result_1<br/>'.mysql_error());
}

$sql_2="INSERT INTO account (acc_type, email, password) VALUES ('$Acctype', '$Email', '$Pswrd')";

$result_2 = mysql_query($sql_2);
if (!$result_2)
{
die('Sorry, could not query the database! result_2<br/>'.mysql_error());
}

$sql_3="INSERT INTO companyprof (comp_name) VALUES ('$Cname')";

$result_3 = mysql_query($sql_3);
if (!$result_3)
{
die('Sorry, could not query the database! result_3<br/>'.mysql_error());
}
header('location:signup.php?reg_4=success');
}
}
...

As you can see, though the tables are related, I've used 3 different queries to insert the data. I suppose there's an efficient way of doing it but unfortunately I don't know how :confused:

I'll be very grateful if someone could help me out :)

TheBearMay
01-14-2009, 12:33 PM
You have already posed this question in another thread.