Insert into data fail after foreign key rebuilded.Mysql PHP - php

I hava two table:IDCa and IDCb.At the beginning, each table has data and works fine. Table IDCb has foreign key sheetNum with IDCa's primary key sheetNum.
When I renamed IDCa to IDCabk,and drop IDCa, it worked failed.
So I runned: set foreign_key_checks=0
, drop table IDCa, create table IDCa like IDCabk.
Now IDCa is empty.After that, I found IDCb's REFERENCES table had changed from IDCa to IDCabk. So I drop IDCb foreign key ,and readded like:
alter table IDCb add constraint fk_dvcOnsh foreign key (sheetNum) references IDCa(sheetNum);
After I runned: set foreign_key_checks=1, and tried insert into data.But unfortunately, it works fail.It seems nothing wrong.
Here IDCa information, run :show create table IDCa :
|IDCa | CREATE TABLE `IDCa` (
`sheetNum` int(255) NOT NULL AUTO_INCREMENT,
.........
PRIMARY KEY (`sheetNum`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
Here IDCb information, run: show create table IDCb :
|IDCb | CREATE TABLE `IDCb` (
`id` int(255) NOT NULL AUTO_INCREMENT,
......
`sheetNum` int(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_dvcOnsh` (`sheetNum`),
CONSTRAINT `fk_dvcOnsh` FOREIGN KEY (`sheetNum`) REFERENCES `IDCa` (`sheetnum`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8
My code of inserting into data:
$conn->beginTransaction();
$query="insert into IDCa(xxx) values('aaa')";
$stmt=$conn->query($query);
$stmt->closeCursor();
$query="insert into IDCb(rrr,sheetNum) values('aaa',LAST_INSERT_ID())";
$stmt=$conn->query($query);
$stmt->closeCursor();
$conn->commit();
Show Error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`hpc`.`IDCb`, CONSTRAINT `fk_dvcOnsh` FOREIGN KEY (`sheetnum`) REFERENCES `IDCa` (`sheetnum`))fail

Related

SQL: Insert..ON DUPLICATE KEY isn't working

My query, in PHP, is:
$upd2 = $di->getDb()->prepare('INSERT INTO '. self::TABLE . '_agrupamento_avaliacao (idSemana, idEntidade_agrupamento) VALUES(?, ?) ON DUPLICATE KEY UPDATE idEntidade_agrupamento=VALUES(idEntidade_agrupamento)');
$upd2->Execute(array($semana, $agrupamento));
But it isn't working. It's inserting the same data.
I tested querying:
INSERT INTO entidade_agrupamento_avaliacao (idSemana, idEntidade_agrupamento) VALUES(17, 2808) ON DUPLICATE KEY UPDATE idEntidade_agrupamento=VALUES(idEntidade_agrupamento)
But it also insert the same data instead of update the data.
My table is:
CREATE TABLE `entidade_agrupamento_avaliacao` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`idSemana` INT(10) UNSIGNED NOT NULL,
`idEntidade_Agrupamento` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK__semana` (`idSemana`),
INDEX `FK_entidade_agrupamento_avaliacao_entidade_agrupamento` (`idEntidade_Agrupamento`),
CONSTRAINT `FK__semana` FOREIGN KEY (`idSemana`) REFERENCES `semana` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_entidade_agrupamento_avaliacao_entidade_agrupamento` FOREIGN KEY (`idEntidade_Agrupamento`) REFERENCES `entidade_agrupamento` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4
;
What is the problem?
Consider "$di->getDb()->prepare" as the PDO Statement prepare.
This is your query:
INSERT INTO '. self::TABLE . '_agrupamento_avaliacao (idSemana, idEntidade_agrupamento)
VALUES(?, ?)
ON DUPLICATE KEY UPDATE idEntidade_agrupamento = VALUES(idEntidade_agrupamento)');
The only unique index that you have on the table is the primary key on id. This is auto-incremented, so it is not going to generate a duplicate.
Presumably, you want to declare idSemana as being unique. Then the duplicate key can be caught. You were probably thinking that index idSemana is sufficient for this purpose, but you really need unique idSemana.

Get the value when a MySQL constraint fails

Assuming I am inserting rows in a MySQL table with a constraint
CREATE TABLE `parent` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;
CREATE TABLE `child` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_parent` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK_parent_child` (`id_parent`),
CONSTRAINT `FK_parent_child` FOREIGN KEY (`id_parent`) REFERENCES `parent` (`id`),
)
ENGINE=InnoDB
;
Then when I do an insert in the child table without the entry in the parent table:
INSERT INTO child (id, id_parent) VALUES (1, 1);
I get the following error:
Cannot add or update a child row: a foreign key constraint fails (`...`.`child`, CONSTRAINT `FK_parent_child` FOREIGN KEY (`id_parent`) REFERENCES `parent` (`id`))`
But is there a way to retrieve the value of the insert-failed row, aka 1 here? Because when I insert thousands of rows at the same time, it would be very useful to get the failed one.
I would like a fully-MySQL way, but a PHP way would work too in my case.

PHP constraint violation Error 1452 ("Cannot add or update a child row")

I have a big problem with this SQL error when I'm trying to insert a event in my database with this PDO.
SQL:
$subsquery1 = "SELECT cat_id FROM categories WHERE cat_name = ".$event_cat;
$subsquery2 = "SELECT tournament_id FROM tournaments WHERE tournament_name = ".$event_tournament;
$sqlx = "INSERT INTO events(event_team1, event_team2, event_cat, event_tournament, event_start_at, event_end_to, event_by) VALUES(:event_team1, :event_team2, :event_cat, :event_tournament, :event_start_at, :event_end_to, :event_by)";
// Prepare statement
$statementx = $pdo->prepare($sqlx);
// execute the query
$resultx = $statementx->execute(array(':event_team1' => $event_team1, ':event_team2' => $event_team2, ':event_cat'=> $subsquery1, ':event_tournament'=> $subsquery2, ':event_start_at' => $event_start_at, ':event_end_to' => $event_end_to,':event_by'=>$event_by));
SQL error:
Integrity constraint violation: 1452 Cannot add or update a child
row: a foreign key constraint fails (datenbank.events, CONSTRAINT
events_ibfk_1 FOREIGN KEY (event_cat) REFERENCES categories
(cat_id) ON DELETE CASCADE ON UPDATE CASCADE)
-- Table structure for table `events`
CREATE TABLE `events` (
`event_id` int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`event_team1` varchar(255) NOT NULL,
`event_team2` varchar(255) NOT NULL,
`event_start_at` timestamp NOT NULL,
`event_end_to` timestamp NOT NULL,
`event_cat` int(8) NOT NULL,
`event_by` int(8) NOT NULL,
`event_tournament` int(8) NOT NULL,
KEY `event_cat` (`event_cat`),
KEY `event_by` (`event_by`),
KEY `event_tournament` (`event_tournament`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Constraints for table posts
ALTER TABLE `posts` ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`post_event`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`post_by`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
-- Constraints for table events
ALTER TABLE `events` ADD CONSTRAINT `events_ibfk_1` FOREIGN KEY (`event_cat`) REFERENCES `categories` (`cat_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `events_ibfk_2` FOREIGN KEY (`event_by`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `events_ibfk_3` FOREIGN KEY (`event_tournament`) REFERENCES `tournaments` (`tournament_id`) ON DELETE CASCADE ON UPDATE CASCADE;
What can I try to solve this?
Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (datenbank.events,
CONSTRAINTevents_ibfk_1FOREIGN KEY (event_cat)
REFERENCEScategories(cat_id)
You are performing an insert to table events with a value being placed in column event_cat.
That value does not already exist in table categories in the column cat_id.
And you said it must. So the db engine says it won't do it. It is faithfully obeying your orders.

Integrity constraint violation: 1452 however the records exist in the 'parent tables'

Im battling with a php and mysql again. I keep encountering a SQL violation error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (insights.proposal, CONSTRAINT proposal_ibfk_1 FOREIGN KEY (course_code) REFERENCES course_details (course_code))
however, when i serialise the information from a php form ready to use in my insert query i encounter this SQL error. I know the course_code and user_record_id are not a problem because i have manually inserted these using the PhpMyAdmin and it has added the record successfully.
The values from the form are okay too. I have used var_dump to see whats being held in the variables and it is correct.
The structure for proposal table:
--
-- Table structure for table `proposal`
--
DROP TABLE IF EXISTS `proposal`;
CREATE TABLE IF NOT EXISTS `proposal` (
`proposal_id` int(11) NOT NULL,
`source` enum('Student','Supervisor','Other') NOT NULL,
`proposal_title` text NOT NULL,
`description` text NOT NULL,
`date_added` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`course_code` int(11) NOT NULL,
`user_record_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
--
-- RELATIONS FOR TABLE `proposal`:
-- `course_code`
-- `course_details` -> `course_code`
-- `user_record_id`
-- `user` -> `user_record_id`
--
ALTER TABLE `proposal`
ADD PRIMARY KEY (`proposal_id`), ADD KEY `course_code` (`course_code`,`user_record_id`), ADD KEY `user_record_id` (`user_record_id`);
ALTER TABLE `proposal`
ADD CONSTRAINT `proposal_ibfk_1` FOREIGN KEY (`course_code`) REFERENCES `course_details` (`course_code`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `proposal_ibfk_2` FOREIGN KEY (`user_record_id`) REFERENCES `user` (`user_record_id`) ON DELETE CASCADE ON UPDATE CASCADE;
my insert query:
$insertProp = $db_conx->prepare(" INSERT INTO `insights`.`proposal` (`source`, `proposal_title`, `description`, `date_added`, `course_code`, `user_record_id`) VALUES ('Supervisor', ':title', ':description', CURRENT_TIMESTAMP, ':course', ':user_record_id')");
$insertProp->bindParam(':user_record_id', $user_record_id, PDO::PARAM_STR);
$insertProp->bindParam(':title', $title, PDO::PARAM_STR);
$insertProp->bindParam(':description', $description, PDO::PARAM_STR);
$insertProp->bindParam(':course', $course, PDO::PARAM_STR);
$insertProp->execute();
Anyone know why its having an issue and a possible workaround please?
Thanks

Foreign key constraint failure [duplicate]

This question already has answers here:
Why 'foreign key constraint fails' when foreign key exists?
(3 answers)
Closed 8 years ago.
I'm working on a new script which has a foreign key error.
I have the following tables: request, category and request_category.
There are now 6 categories in table category, so that's all good.
My script inserts the data into the request table and after that it tries to add an entry to request_category but this is where it fails.
The code:
$oUser = new User();
$oUser->firstname = $this->oLibrary->Request->post('firstname');
$oUser->initials = $this->oLibrary->Request->post('initials');
$oUser->lastname = $this->oLibrary->Request->post('lastname');
$oUser->zip = $this->oLibrary->Request->post('zip');
$oUser->city = $this->oLibrary->Request->post('city');
$oUser->email = $this->oLibrary->Request->post('email');
$oUser->setStatus(UserStatus::STATUS_PENDING);
$oUser->create();
$oRequest = new ServiceRequest();
$oRequest->title = $this->oLibrary->Request->post('title');
$oRequest->description = $this->oLibrary->Request->post('description');
$oRequest->user_id = $oUser->id;
$oRequest->setStatus(RequestStatus::STATUS_INCOMPLETE);
$oRequest->create();
// above here goes fine
$oRequestCategory = new RequestCategory();
$oRequestCategory->category_id = $this->oLibrary->Request->post('category');
$oRequestCategory->request_id = $oRequest->id;
$oRequestCategory->create();
I don't quite understand why it won't insert. I have checked and both keys the request_table requires are present in the database. When I try to do the insert in Workbench it throws the same error, So I guess it's a flaw in my database design somewhere. Could someone explain to me why I'm getting this foreign key error?
The error message itself:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`ruiljedienst`.`request_category`, CONSTRAINT `fk_request_category_category1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
INSERT INTO `ruiljedienst`.`request_category` (`category_id`, `request_id`) VALUES ('1', '1')
Here's a screenshot of the related database tables in MySQL workbench:
http://prntscr.com/2fwce6
Update:
show create table ruiljedienst.request_category
Results in :
CREATE TABLE `request_category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`request_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_request_category_category1_idx` (`category_id`),
KEY `fk_request_category_request1_idx` (`request_id`),
CONSTRAINT `fk_request_category_category1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_request_category_request1` FOREIGN KEY (`request_id`) REFERENCES `request` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1'
select id from ruiljedienst.category
This gives:
http://prntscr.com/2fwhfl
You have a foreign key constraint on category_id, so you have to add id=1 to the category table before you add the row to request_category.
Make sure that all the referenced tables use ENGINE=InnoDB.

Categories