473,383 Members | 1,891 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Cannot add or update a child row: a foreign key constraint fails (`kims`.`question`,

semanticnotion
Hi sir i want to transform the data of one table into another through foreign key but the following error come to my browser
Cannot add or update a child row: a foreign key constraint fails (`kims`.`question`, CONSTRAINT `fk_question_subject` FOREIGN KEY (`sub_code`) REFERENCES `subject` (`subject_code`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Here is my code and data base structure.

Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE IF NOT EXISTS `subject` (
  2.   `subject_code` int(11) NOT NULL AUTO_INCREMENT,
  3.   `Name` text,
  4.   PRIMARY KEY (`subject_code`)
  5. ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=105 ;
  6.  
  7. --
  8. -- Dumping data for table `subject`
  9. --
  10.  
  11. INSERT INTO `subject` (`subject_code`, `Name`) VALUES
  12. (101, 'computer sciense'),
  13. (102, 'Maths'),
  14. (103, 'English'),
  15. (104, 'Chemistry');
  16.  
  17. *********************************************************
  18.  
  19. and the question table is:
  20.  
  21. CREATE TABLE IF NOT EXISTS `question` (
  22.   `question_id` int(11) NOT NULL AUTO_INCREMENT,
  23.   `question` text,
  24.   `weight` int(11) DEFAULT NULL,
  25.   `sub_code` int(11) NOT NULL,
  26.   PRIMARY KEY (`question_id`,`sub_code`),
  27.   KEY `fk_question_subject` (`sub_code`)
  28. ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=205 ;
  29.  
  30. --
  31. -- Dumping data for table `question`
  32. --
  33.  
  34.  
  35. --
  36. -- Constraints for dumped tables
  37. --
  38.  
  39. --
  40. -- Constraints for table `question`
  41. --
  42. ALTER TABLE `question`
  43.   ADD CONSTRAINT `fk_question_subject` FOREIGN KEY (`sub_code`) REFERENCES `subject` (`subject_code`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Here is my code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3.  
  4. session_start();
  5.  
  6.  include("conn.php");
  7.      connect();
  8. if($_GET['action']=="add")
  9. {
  10.  
  11. //$sub_code=$_POST['sub_code'];
  12. $sub_name=$_POST['sub_name'];
  13.  
  14.  
  15. $result=mysql_query("insert into subject values('','$sub_name')") or die(mysql_error());
  16.  
  17. /*echo "<script>window.alert('News Added Successfully') </script>";*/
  18. }
  19. ?>
  20. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  21. <html xmlns="http://www.w3.org/1999/xhtml">
  22. <head>
  23. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  24. <title>Untitled Document</title>
  25. <link href="KIMS-CSS.css" rel="stylesheet" type="text/css" />
  26. <style type="text/css">
  27. <!--
  28. .style1 {font-size: 14px}
  29. -->
  30. </style>
  31.  
  32.  
  33. <body>
  34. <?php
  35. $access = $_SESSION["access"];
  36. if ($access != "authorized")
  37. echo "<script>window.alert('You are not allowed to use this page'); window.location.replace('main_login.php'); </script>";
  38.  
  39. ?>
  40. <TABLE width="90%" border="0">
  41.   <TR>
  42.     <TD class="blue-17-bold"><DIV align="center" class="table-title-row style1">Add Subject </DIV></TD>
  43.   </TR>
  44. </TABLE>
  45. <p>&nbsp;</p>
  46. <form id="form1" name="form1" method="post" action="add_subject.php?action=add">
  47.   <table width="356" border="1" align="center">
  48.  
  49.     <tr>
  50.       <td>Subject Name</td>
  51.       <td><input name="sub_name" type="text" id="descrip" onchange="return change(this)"/></td>
  52.     </tr>
  53.     <tr>
  54.       <td colspan="2" align="center"><div>
  55.         <label>
  56.         <input name="Submit" type="submit" id="Submit" value="Add Subject" />
  57.         </label>
  58.       </div></td>
  59.     </tr>
  60.   </table>
  61. </form>
  62. <div>
  63.   <div align="center" class="table-title-row style1">Show Subjects </div>
  64. </div>
  65. <p>&nbsp;</p>
  66.  
  67. <table width="716" border="1">
  68.   <tr>
  69.     <td width="105">Subject Code</td>
  70.     <td width="110">Subject Name</td>
  71.  
  72.     <td width="66">Delete</td>
  73.       </tr>
  74.   <?php
  75.  
  76. $select=mysql_query("select * from subject") or die(mysql_error());
  77.  
  78.  
  79.  
  80. while($rs=mysql_fetch_array($select))
  81. {
  82.          $var=$rs[subject_code];
  83.           $sub=$rs[Name];
  84. ?>
  85.   <tr>
  86.     <td><?php echo $rs['subject_code']; ?></td>
  87.     <td><?php echo "<a href='add_question.php?code=$var&Name=$sub'> $rs[Name]</a><br/>"; ?></td>
  88.     <td><a href="delete_subject.php?id=<?php echo $rs['subject_code']; ?>">Delete</a></td>
  89.   </tr>
  90.   <?php
  91.   }
  92.   ?>
  93. </table>
  94. </body>
  95. </html>
  96.  
and the add question page code is:

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3. session_start();
  4. include("conn.php");
  5.      connect();
  6. $sub_code=$_GET['code'];
  7. echo"$sub_code";
  8.  
  9. if($_GET['action']=="add")
  10. {
  11.  
  12.  
  13. //$sub_code=$_POST['sub_code'];
  14. $question=$_POST['question'];
  15. $weight=$_POST['weight'];
  16.  
  17. $result=mysql_query("insert into question values('','$question','$wieght','sub_code')") or die(mysql_error());
  18.  
  19. //*echo "<script>window.alert('News Added Successfully') </script>";*/
  20. }
  21. ?>
  22. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  23. <html xmlns="http://www.w3.org/1999/xhtml">
  24. <head>
  25. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  26. <title>Untitled Document</title>
  27. <link href="KIMS-CSS.css" rel="stylesheet" type="text/css" />
  28. <style type="text/css">
  29. <!--
  30. .style1 {font-size: 14px}
  31. -->
  32. </style>
  33.  
  34. </head>
  35. <body>
  36. <?php
  37. $access = $_SESSION["access"];
  38. if ($access != "authorized")
  39. echo "<script>window.alert('You are not allowed to use this page'); window.location.replace('main_login.php'); </script>";
  40.  
  41. ?>
  42. <table width="90%" border="0">
  43.   <tr>
  44.     <td class="blue-17-bold"><div align="center" class="table-title-row style1">Add Question </div></td>
  45.   </tr>
  46. </table>
  47. <p>&nbsp;</p>
  48. <form id="form1" name="form1" method="post" action="add_question.php?action=add">
  49.   <table width="356" border="1" align="center">
  50.  
  51.     <tr>
  52.       <td>Question</td>
  53.       <td><input name="question" type="text" id="descrip" onchange="return change(this)"/></td>
  54.     </tr>
  55. <tr>
  56.       <td>Weight</td>
  57.       <td><input name="weight" type="text" id="descrip" onchange="return change(this)"/></td>
  58.     </tr>
  59.     <tr>
  60.       <td colspan="2" align="center"><div>
  61.         <label>
  62.         <input name="Submit" type="submit" id="Submit" value="Add Subject" />
  63.         </label>
  64.       </div></td>
  65.     </tr>
  66.   </table>
  67. </form>
  68. <div>
  69.   <div align="center" class="table-title-row style1">Show Subjects </div>
  70. </div>
  71. <p>&nbsp;</p>
  72.  
  73. <table width="716" border="1">
  74.   <tr>
  75.     <td width="105">Question Id    </td>
  76.     <td width="110">Question</td>
  77. <td width="110">Wieght</td>
  78. <td width="110">Subject Code</td>
  79.  
  80.     <td width="66">Delete</td>
  81.       </tr>
  82.   <?php
  83.  
  84. $select=mysql_query("select * from question") or die(mysql_error());
  85.  
  86.  
  87.  
  88. while($rs=mysql_fetch_array($select))
  89. {
  90.          $var=$rs[question_id];
  91.           $sub=$rs[question];
  92. ?>
  93.   <tr>$sub_code=$_GET['code'];
  94.     <td><?php echo $rs['question_id']; ?></td>
  95.     <td><?php echo "<a href='add_answer.php?code=$var&Name=$sub'> $rs[questin]</a><br/>"; ?></td>
  96. <td><?php echo $rs['weight']; ?></td>
  97. <td><?php echo  $rs['sub_code']; ?></td>
  98.  
  99.     <td><a href="delete_subject.php?id=<?php echo $rs['question_id']; ?>">Delete</a></td>
  100.   </tr>
  101.   <?php
  102.   }
  103.   ?>
  104. </table>
  105. </body>
  106. </html>
  107.  
when i run this the following error occur
Cannot add or update a child row: a foreign key constraint fails (`kims`.`question`, CONSTRAINT `fk_question_subject` FOREIGN KEY (`sub_code`) REFERENCES `subject` (`subject_code`) ON DELETE NO ACTION ON UPDATE NO ACTION)

plz help thanks in advance....
Sep 28 '10 #1
6 4881
JKing
1,206 Expert 1GB
You cannot insert data into a child table if the key does not exist in the parent table.

So in your case the related subject must exist before you insert a question for that subject.
Sep 28 '10 #2
THANKS jking for your response,
i have already insert the subject before add the related question you can see it my data base table e.g 101 computer science. But the same error occur.
Sep 29 '10 #3
JKing
1,206 Expert 1GB
I think I may have spotted the source of your problem

Expand|Select|Wrap|Line Numbers
  1. $result=mysql_query("insert into question values('','$question','$wieght','sub_code')") or die(mysql_error());
  2.  
There is no $ in front of your sub_code variable so it is trying to insert the value "sub_code" and not the variable.
Sep 29 '10 #4
I put $sub_code in query but still it not working. It take one question but when i insert another question it gives the above error.
Expand|Select|Wrap|Line Numbers
  1. $query="INSERT INTO  `kims`.`question` (`question` ,`weight` ,`sub_code`)VALUES ('$question',  '$weight',  '$sub_code')";
  2.  
Sep 30 '10 #5
JKing
1,206 Expert 1GB
I think you need to possibly rework your form and rethink some of your logic here.

If you echo out your query before you run it, I think it will help illustrate your problem. You are rewriting your sub code variable to an empty string when you submit your add question form.
Sep 30 '10 #6
yap i echo the query at first it take the value of $sub_code but when i insert another question the $sub_code is empty whats the reason of this i am not sure where i have a mistake.
Oct 4 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Ralph Smith | last post by:
I'm having trouble copying a database to another machine. Here are the two table's in ths database and the sql commands: DROP TABLE IF EXISTS `clients`; CREATE TABLE `clients` ( `client_id`...
4
by: Frank | last post by:
Hello, I have a dataset with 2 tables and a relation (parent - child). I linked that ds to a datagrid. Shows everything fine (very little coding for such functionality!). But.. in the child row I...
3
by: fuimens | last post by:
Hi, With mysql-4.0.20, I have a problem inserting data with foreign key references, MySQL saying ERROR 1216: Cannot add or update a child row: a foreign key constraint fails The message is...
0
by: Zorglub | last post by:
Hi, I have a windos form with two datagrids Master and Detail, I use a dataset with two datatable and a relation between Table1 and Table2. I set the datagrid like : DataViewManager dsView =...
3
by: Ivan | last post by:
Thanks to answer topic previous!!!! I use this script to update one table MERGE INTO EIS.CLI_HISTORY TXN USING EIS.CLI_MAPING CLI ON TXN.CLIENTID = CLI.CLIENTID WHEN MATCHED AND...
4
by: Harshpandya | last post by:
Hi I am new at ASP and MYSQL. I am Using Navicat to access MYSQL database. My Problem is when i create the foreign key in "Navicat" -it gives me this error. 1452-cannot add or update child...
1
by: nitinkhare1 | last post by:
Please help,I'm very frustated. when I ADD the data in kn_history_question table of htbase_tst database....it giving the error "Cannot add or update a child row:a foreign key constraint...
3
by: nzaiser | last post by:
Hello! This is my first time asking a question here, so please bear with me if I seem 'unconventional!' My issue is this..... OS: Windows_NT App: MS Access 2000 (also in 2003) ODBC linked...
0
muaddubby
by: muaddubby | last post by:
Hi I've got a situation with a dataset that contains two tables with a many-to-one relationship, and am trying to extract the data in xml format. When I execute the GetXml() method, and exception...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.