Jump to content

FOREIGN KEY Constraint


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
https://forums.phpfreaks.com/topic/285784-foreign-key-constraint/
Share on other sites

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

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

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.