Search code examples
phpmysqldatabaseforeign-key-relationship

Cannot add or update a child row: a foreign key constraint fails (Mysql and Foreign key)


When I trying to run the code, this error shows up

Cannot add or update a child row: a foreign key constraint fails (hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY (CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE ON UPDATE CASCADE)

Here is the code

$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
            if (false === $result) 
            {
                echo     mysql_error();
            }

if (isset($_POST["submitbtn"]))
{
    $LP = $_POST["LP"];
    $budget = $_POST["budget"];
    $checkin = $_POST["CheckIn"];
    $checkout = $_POST["CheckOut"];
    $unit = $_POST["unit"];
    $smokep = $_POST["SmokeP"];
    $spreq = $_POST["sp_req"];


        if($checkin>$checkout)
        {
        ?>
        <script type="text/javascript">
                alert("End Date must greater than Start Date.");
        </script>           

        <?php
        }
        else
        {
            $query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget', 
                                        '$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");    

            if (false === $query) 
            {
                echo     mysql_error();
            }

            echo "Reservation form has been submitted!<br>
                <a href=view.php>view all</a>";

        }
}

Here is the sql

CREATE TABLE IF NOT EXISTS `results` (
  `BookID` int(10) NOT NULL AUTO_INCREMENT,
  `LP` varchar(50) DEFAULT NULL,
  `budget` varchar(50) DEFAULT NULL,
  `CheckIn` varchar(50) DEFAULT NULL,
  `CheckOut` varchar(50) DEFAULT NULL,
  `unit` int(50) DEFAULT NULL,
  `SmokeP` varchar(50) DEFAULT NULL,
  `sp_req` varchar(255) DEFAULT NULL,
  `CustomerID` int(10) NOT NULL,
  PRIMARY KEY (`BookID`),
  KEY `Username` (`CustomerID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;

CREATE TABLE IF NOT EXISTS `customer` (
  `CustomerID` int(10) NOT NULL AUTO_INCREMENT,
  `Username` varchar(50) NOT NULL,
  `Password` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `ContactNo` int(10) NOT NULL,
  PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

I've already stuck for two days because of this error, please help.


Solution

  • from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id