473,763 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

semanticnotion
66 New Member
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`.`questi on`, CONSTRAINT `fk_question_su bject` 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`.`questi on`, CONSTRAINT `fk_question_su bject` 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 4914
JKing
1,206 Recognized Expert Top Contributor
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
semanticnotion
66 New Member
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 Recognized Expert Top Contributor
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
semanticnotion
66 New Member
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 Recognized Expert Top Contributor
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
semanticnotion
66 New Member
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
36261
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` int(10) unsigned NOT NULL auto_increment, `lastname` char(15) NOT NULL default '', `firstname` char(15) NOT NULL default '', `birthdate` date NOT NULL default '0000-00-00',
4
2893
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 want to show a column of the parent. Example: orderColumn shows customerId and I want the customerName which is located in the parent. How do I do that? Thanks in advance Frank
3
5447
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 confusing because a parent record in parent table exists !? The "show innodb status; " command prints :
0
1195
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 = myDataSet.DefaultViewManager; dataGrid1.DataSource = dsView; dataGrid1.DataMember = "NAMEFIRSTTABLE"; dataGrid2.DataSource = dsView; dataGrid2.DataMember = "NAMERELATION";
3
6831
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 CLI.STATUSID = 3 AND CLI.CLIENTID != CLI.MAPPEDCLIENTID AND
4
9850
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 row: a foreign key constraint fails.... Can any body help me - why am i getting this error - and how to fix it --
1
5969
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 fails,<'htbase_tst/kn_history_question', CONSTRAINT 'FK_kn_history_question_complaint' FOREIGN KEY ('complaint_id' ) REFERENCES 'complaint'('id')). This is my table script..... CREATE TABLE `city` ( `id` int(11) NOT NULL auto_increment, ...
3
13301
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 table into a DB for which I have read/write/delete authority. I have verified the authority in the source DB - ad nauseum - it works. Tested the table in question (Region) specifically and another table (Store_Info) as well. I can open the Region...
0
2662
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 is thrown telling me that "A child row has multiple parents", and the xml is obviously not generated. The output I'm expecting is something like this: <parent> <parentRecnum>1</parentRecnum> <childRecnum>1</childRecnum> <child>
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10145
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.