Dear Good ever responding friends,
I have the error that held me down for sometime. I always recieve this mail "'Cannot add or update a child row: a foreign key constraint fails" whenever i try to submit data. Does it mean my foriegn key is not prperly set? I don't seem to find the problem. Below is the mysql code and php newcustomer code respectively:
-- phpMyAdmin SQL Dump
-- version 3.2.0.1
--
http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: May 07, 2010 at 08:40 PM
-- Server version: 5.1.41
-- PHP Version: 5.3.0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `bank`
--
-- --------------------------------------------------------
--
-- Table structure for table `accounts`
--
CREATE TABLE IF NOT EXISTS `accounts` (
`accid` int(4) NOT NULL AUTO_INCREMENT,
`accno` varchar(10) NOT NULL,
`balance` int(11) NOT NULL,
`type` varchar(100) NOT NULL,
`active` varchar(5) NOT NULL,
PRIMARY KEY (`accid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `accounts`
--
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE IF NOT EXISTS `customer` (
`cusid` int(4) NOT NULL AUTO_INCREMENT,
`busname` varchar(50) NOT NULL,
`busnat` varchar(50) NOT NULL,
`name` varchar(50) NOT NULL,
`address` text NOT NULL,
`email` varchar(50) NOT NULL,
`avermon` varchar(50) NOT NULL,
`nextkin` varchar(50) NOT NULL,
`pin` varchar(10) NOT NULL,
`picture` blob NOT NULL,
`sign` blob NOT NULL,
`date` date NOT NULL,
`acc_id` int(4) NOT NULL,
PRIMARY KEY (`cusid`),
KEY `INDEX` (`acc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `customer`
--
--
-- Constraints for dumped tables
--
--
-- Constraints for table `customer`
--
ALTER TABLE `customer`
ADD CONSTRAINT `customer_ibfk_1` FOREIGN KEY (`acc_id`) REFERENCES `accounts` (`accid`) ON DELETE CASCADE ON UPDATE CASCADE;
and the newcustomer php code:
function newcustomer($accno,$type,$balance,$active,$name,$pin,$address,$email,$picture,$busname,$busnat,$sign ,$date,$avermon,$nextkin){
//first insert customer details, then use the newly generated id
$sql = "INSERT INTO customer (name,busname,busnat,address,email,date,avermon,nextkin,picture,sign,pin) values ('".$name."','".$busname."','".$busnat."','".$address."','".$email."','".$date."','".$avermon."','". $nextkin."','".$picture."','".$sign."','".$pin."')";
if(!mysql_query($sql)){
throw new Exception(mysql_error());
return FALSE;
}else{
$newid = mysql_insert_id();
return TRUE;
}
if($newid > 0){
$sql_acc = "INSERT INTO accounts (accno,type,balance,active,cusid) values ('".$accno."','".$type."','".$balance."','1','".$newid."')";
if(!mysql_query($sql_acc)){
throw new Exception(mysql_error());
}
return TRUE;
}
}
Thanks in advance.