Jump to content

FOREIGN KEY Constraint


arunpatal
Go to solution Solved by arunpatal,

Recommended Posts

I created two tables.

mysql_query("CREATE TABLE IF NOT EXISTS $answers(
	
		aid int UNSIGNED auto_increment primary key,
		answers varchar(255) NOT NULL
		
	)") or die (mysql_error());
	
	mysql_query("CREATE TABLE IF NOT EXISTS $questions(
		
		qid int auto_increment primary key,
		question varchar(455) NOT NULL,
		an_id int(11) UNSIGNED NOT NULL,
		FOREIGN KEY (an_id) REFERENCES $answers(aid),
		added_on date
		
	)") or die (mysql_error());

Now i am inserting data via form

$question = mysql_real_escape_string($_POST["question"]);
		$answer = mysql_real_escape_string($_POST["answer"]);
		$date = date('Y-m-d');
		
mysql_query("INSERT INTO $answers (answers) VALUES ('$answer')")
			or die (mysql_error());
			
mysql_query("INSERT INTO $questions (question,added_on) VALUES ('$question','$date')")
			or die (mysql_error());

But i am facing this error...

Cannot add or update a child row: a foreign key constraint fails (`german_quiz`.`questions`, CONSTRAINT `questions_ibfk_1` FOREIGN KEY (`an_id`) REFERENCES `answers` (`aid`))

Please help

Link to comment
Share on other sites

  • Solution

You need to get the ID generated when you insert your answer and then pass that to the questions insert. You can get the last generated ID using mysql_insert_id.

 

You should also start moving away from the mysql_* functions and re-writing your code to use either PDO (my recommendation) or MySQLI

 

mysql_insert_id works :)

 

thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.