Error:
Cannot delete or update a parent row: a foreign key constraint fails
(`databasename`.`webapp_requestsuser`, CONSTRAINT `fk_perRequests` FOREIGN KEY
(`requestsid`) REFERENCES `webapp_requests` (`id`))
Create Queries:
CREATE TABLE `webapp_requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`opentime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`starttime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`description` longtext,
`duration` double DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE `webapp_requestsuser` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` int(11) NOT NULL,
`status` tinyint(4) DEFAULT '0',
`requestsid` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `requestsid` (`requestsid`),
CONSTRAINT `fk_perRequests` FOREIGN KEY (`requestsid`) REFERENCES `webapp_requests` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
Content webapp_requests:
_______________________________________
| id = 2 |
| userid = 2 |
| opentime = 2015-11-24 16:26:44 |
| starttime = 2015-11-24 16:26:44 |
| description = This is a description |
| duration = 5.0 |
_______________________________________
Content webapp_requestsuser:
_______________________________________
| id = 3 |
| user = 1 |
| status = 0 |
| requestsid = 2 |
_______________________________________
Delete Query:
DELETE FROM `webapp_requests` WHERE `id` = 2;
This is what I get all the time when I want to delete a row in webapp_requests.
I seriously tried every possible question already asked on here and couldn't solve it. And yes I know how FKs work. Further I use this function to Insert data:
public function createRequest($userid, $recipients, $description, $duration, $starttime)
{
$existcheck = $this->db->query('SELECT * FROM `webapp_requests` WHERE `userid`=('.$this->db->escape($userid).')');
// Check if already a request is registered
if ($existcheck->num_rows() > 0) {
return false;
}
// First add the request
$query = $this->db->query('INSERT INTO `webapp_requests`( `userid`, `description`, `duration`, `starttime`) VALUES (' . $this->db->escape($userid) . ',' . $this->db->escape($description) . ',' . $this->db->escape($duration) . ',' . $this->db->escape($starttime) . ')');
$id = $this->db->insert_id();
if (!$query) {
return false;
} else {
// Then add the users to the request
$tokens = [];
foreach($recipients as $recipient) {
$this->db->query('INSERT INTO `webapp_requestsuser`(`user`,`requestsid`) VALUES (' . $this->db->escape($recipient) . ',' . $this->db->escape($id) . ')');
$pushValue = $this->db->query('SELECT * FROM `notificationtoken` WHERE `user`=('.$this->db->escape($recipient).')')->row();
array_push($tokens, $pushValue);
}
return $tokens;
}
}