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

  php

Q(Question):

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.

CREATE TABLE IF NOT EXISTS `subject` (
`subject_code` int(11) NOT NULL AUTO_INCREMENT,
`Name` text,
PRIMARY KEY (`subject_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=105 ;
--
-- Dumping data for table `subject`
--
INSERT INTO `subject` (`subject_code`, `Name`) VALUES
(101, 'computer sciense'),
(102, 'Maths'),
(103, 'English'),
(104, 'Chemistry');
*********************************************************
and the question table is:
CREATE TABLE IF NOT EXISTS `question` (
`question_id` int(11) NOT NULL AUTO_INCREMENT,
`question` text,
`weight` int(11) DEFAULT NULL,
`sub_code` int(11) NOT NULL,
PRIMARY KEY (`question_id`,`sub_code`),
KEY `fk_question_subject` (`sub_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=205 ;
--
-- Dumping data for table `question`
--
--
-- Constraints for dumped tables
--
--
-- Constraints for table `question`
--
ALTER TABLE `question`
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:


<?php
session_start();
include("conn.php");
connect();
if($_GET['action']=="add")
{
//$sub_code=$_POST['sub_code'];
$sub_name=$_POST['sub_name'];
$result=mysql_query("insert into subject values('','$sub_name')") or die(mysql_error());
/*echo "<script>window.alert('News Added Successfully') </script>";*/
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="KIMS-CSS.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style1 {font-size: 14px}
-->
</style>
<body>
<?php
$access = $_SESSION["access"];
if ($access != "authorized")
echo "<script>window.alert('You are not allowed to use this page'); window.location.replace('main_login.php'); </script>";
?>
<TABLE width="90%" border="0">
<TR>
<TD class="blue-17-bold"><DIV align="center" class="table-title-row style1">Add Subject </DIV></TD>
</TR>
</TABLE>
<p>&nbsp;</p>
<form id="form1" name="form1" method="post" action="add_subject.php?action=add">
<table width="356" border="1" align="center">
<tr>
<td>Subject Name</td>
<td><input name="sub_name" type="text" id="descrip" onchange="return change(this)"/></td>
</tr>
<tr>
<td colspan="2" align="center"><div>
<label>
<input name="Submit" type="submit" id="Submit" value="Add Subject" />
</label>
</div></td>
</tr>
</table>
</form>
<div>
<div align="center" class="table-title-row style1">Show Subjects </div>
</div>
<p>&nbsp;</p>
<table width="716" border="1">
<tr>
<td width="105">Subject Code</td>
<td width="110">Subject Name</td>
<td width="66">Delete</td>
</tr>
<?php
$select=mysql_query("select * from subject") or die(mysql_error());
while($rs=mysql_fetch_array($select))
{
$var=$rs[subject_code];
$sub=$rs[Name];
?>
<tr>
<td><?php echo $rs['subject_code']; ?></td>
<td><?php echo "<a href='add_question.php?code=$var&Name=$sub'> $rs[Name]</a><br/>"; ?></td>
<td><a href="delete_subject.php?id=<?php echo $rs['subject_code']; ?>">Delete</a></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

and the add question page code is:


<?php
session_start();
include("conn.php");
connect();
$sub_code=$_GET['code'];
echo"$sub_code";
if($_GET['action']=="add")
{
//$sub_code=$_POST['sub_code'];
$question=$_POST['question'];
$weight=$_POST['weight'];
$result=mysql_query("insert into question values('','$question','$wieght','sub_code')") or die(mysql_error());
//*echo "<script>window.alert('News Added Successfully') </script>";*/
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="KIMS-CSS.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style1 {font-size: 14px}
-->
</style>
</head>
<body>
<?php
$access = $_SESSION["access"];
if ($access != "authorized")
echo "<script>window.alert('You are not allowed to use this page'); window.location.replace('main_login.php'); </script>";
?>
<table width="90%" border="0">
<tr>
<td class="blue-17-bold"><div align="center" class="table-title-row style1">Add Question </div></td>
</tr>
</table>
<p>&nbsp;</p>
<form id="form1" name="form1" method="post" action="add_question.php?action=add">
<table width="356" border="1" align="center">
<tr>
<td>Question</td>
<td><input name="question" type="text" id="descrip" onchange="return change(this)"/></td>
</tr>
<tr>
<td>Weight</td>
<td><input name="weight" type="text" id="descrip" onchange="return change(this)"/></td>
</tr>
<tr>
<td colspan="2" align="center"><div>
<label>
<input name="Submit" type="submit" id="Submit" value="Add Subject" />
</label>
</div></td>
</tr>
</table>
</form>
<div>
<div align="center" class="table-title-row style1">Show Subjects </div>
</div>
<p>&nbsp;</p>
<table width="716" border="1">
<tr>
<td width="105">Question Id </td>
<td width="110">Question</td>
<td width="110">Wieght</td>
<td width="110">Subject Code</td>
<td width="66">Delete</td>
</tr>
<?php
$select=mysql_query("select * from question") or die(mysql_error());
while($rs=mysql_fetch_array($select))
{
$var=$rs[question_id];
$sub=$rs[question];
?>
<tr>$sub_code=$_GET['code'];
<td><?php echo $rs['question_id']; ?></td>
<td><?php echo "<a href='add_answer.php?code=$var&Name=$sub'> $rs[questin]</a><br/>"; ?></td>
<td><?php echo $rs['weight']; ?></td>
<td><?php echo $rs['sub_code']; ?></td>
<td><a href="delete_subject.php?id=<?php echo $rs['question_id']; ?>">Delete</a></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

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….

A(Answer):

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.

A(Answer):

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.

A(Answer):

I think I may have spotted the source of your problem


$result=mysql_query("insert into question values('','$question','$wieght','sub_code')") or die(mysql_error());

There is no $ in front of your sub_code variable so it is trying to insert the value "sub_code" and not the variable.

A(Answer):

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.

$query="INSERT INTO `kims`.`question` (`question` ,`weight` ,`sub_code`)VALUES ('$question', '$weight', '$sub_code')";

A(Answer):

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.

A(Answer):

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.

LEAVE A COMMENT