arunpatal Posted January 29, 2014 Share Posted January 29, 2014 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 Quote Link to comment Share on other sites More sharing options...
Barand Posted January 30, 2014 Share Posted January 30, 2014 An unusual type of quiz where each answer has many questions. So given the answer you have to guess what the question was? The ones I've seen before have had the question id as a foreign key in the answer table. Quote Link to comment Share on other sites More sharing options...
arunpatal Posted January 30, 2014 Author Share Posted January 30, 2014 I want aid ($answers table) value to save into an_id ($questions table) Quote Link to comment Share on other sites More sharing options...
kicken Posted January 30, 2014 Share Posted January 30, 2014 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 Quote Link to comment Share on other sites More sharing options...
Solution arunpatal Posted January 30, 2014 Author Solution Share Posted January 30, 2014 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.