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

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.

Related

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.

MYSQL #1136 - Column count doesn't match value count at row 1 though they are equal

I keep getting the following error though no. of columns and no. of values match, so I wonder can someone help ?
INSERT INTO `user_dates` (`id`, `date`, `user_id`) VALUES(26545, '2016-04-28', 35);
My Table structure is:
CREATE TABLE `user_dates` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `user_dates_user_id_foreign` (`user_id`),
CONSTRAINT `user_dates_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10459 DEFAULT CHARSET=utf8;

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.

Foreign key constraint fails in transaction

I'm developing a web-based application with PHP/MySQL + Yii Framework. The problem occurs as a constraint check error in a transaction.
I have the following tables:
User
CREATE TABLE IF NOT EXISTS `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) DEFAULT NULL,
`surname` varchar(64) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`creation_date` datetime DEFAULT NULL,
`last_login_date` datetime DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
`level` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=40 ;
CandidateInfo
CREATE TABLE IF NOT EXISTS `CandidateInfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`candidate_status_id` int(11) DEFAULT NULL,
`name` varchar(64) DEFAULT NULL,
`surname` varchar(64) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`gender` tinyint(1) DEFAULT '0',
`date_of_birth` datetime DEFAULT NULL,
`home_phone` varchar(20) DEFAULT NULL,
`mobile_phone` varchar(20) DEFAULT NULL,
`creation_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`rating` tinyint(1) DEFAULT '0',
`location` varchar(100)DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_candidateinfo_user` (`id`),
KEY `FK_candidateinfo_candidatestatus` (`candidate_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=26 ;
Basically I'm trying to add a new row to User table, and then use the insert id to add a new row to the CandidateInfo table (user_id column)
The php code is as
$transaction = Yii::app()->db->beginTransaction();
try {
$user->save();
$candidate->setAttribute('user_id', $user->id);
$candidate->save();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
var_dump($e->getMessage());
}
The error is:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`origo`.`CandidateInfo`, CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION). The SQL statement executed was: INSERT INTO `CandidateInfo` (`gender`, `rating`, `name`, `surname`, `email`, `date_of_birth`, `home_phone`, `mobile_phone`, `user_id`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8)
When i check the mysql query logs, i see that it takes the right user_id for the INSERT statement for CandidateInfo table. But fails with the above error. From my understanding, it is supposed to work, but may be i am mistaken and this is not the way transactions are meant to work.
Both tables are InnoDB.
Thanks in advance.
Edit:
Sorry forgot to paste the FK relations.
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
should be
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
you've got id references id in yours.
Your error stack:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (origo.CandidateInfo, CONSTRAINT FK_candidateinfo_user FOREIGN KEY (id) REFERENCES User (id) ON DELETE NO ACTION ON UPDATE NO ACTION).
The SQL statement executed was:
INSERT INTO `CandidateInfo`
( `gender`, `rating`, `name`, `surname`, `email`,
`date_of_birth`, `home_phone`, `mobile_phone`, `user_id`
)
VALUES ( :yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8 )
Your CandidateInfo table defines id field as auto_increment primary key field and a foreign key as well.
And your insert statement does not include id, read from its parent user table.
And hence on insert a new id value is generated for candidateinfo table and applied.
Which intern failed as it did not match any of the primary key id value of the parent user table.
And hence is the error.
Note:
In a child table if your are referring a pk field of a master as a foreign key field,
you should not apply auto_increment for it but just refer.
And looking closely the candidateinfo structure, I feel that you might want to map use_id to user.id field. Making that change, with proper foreign key definition used, would resolve your problem.

Categories