I have two tables, users and comments. I need to add firstname and lastname to users and the comments to the comments table with the user id as a foreign key in comments. I am using phpmyadmin to do the add the foreign key constrain and relationships.
This is my html form:
<form action="dbconnect.php" method="post">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br />
Comments: <textarea cols="30" rows="5" name="comments"></textarea><br />
<input type="submit">
</form>
This is my php insert code:
mysql_select_db("test", $db_server);
$sql="INSERT INTO users (Firstname, Lastname)
VALUES
('$_POST[firstname]','$_POST[lastname]')";
$sql="INSERT INTO comments (Comment)
VALUES
('$_POST[comments]')";
if (!mysql_query($sql,$db_server))
{
die('Error' . mysql_error());
}
echo "1 record added" ;
mysql_close($db_server);
and this is the error i'm getting:
Error: Cannot add or update a child row: a foreign key constraint fails (
test
.comments
, CONSTRAINTcomments_ibfk_2
FOREIGN KEY (useridfk
) REFERENCESusers
(id
) ON DELETE CASCADE ON UPDATE CASCADE)
I am new to php and phpmyadmin so any help is appreciated.