One to many relationship in SQL - foreign key error - php

I am trying to create a campus structure. So buildings have floors, floors have rooms. I am trying to create a relational database such that multiple rooms relate to one floor and multiple floors relate to their building.
Here is my structure for the building and floor tables:
CREATE TABLE `building` (
`id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
CREATE TABLE `floor` (
`id` int(11) NOT NULL,
`building_id` int(11) DEFAULT NULL,
`level` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `floor_building_id__fk` (`building_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
I want to insert more than one floor in the floor table relating to the same building_id using:
INSERT INTO `floor` SET id=3, `number` = 420, building_id=(SELECT id FROM building WHERE id=2);
However I keep getting the following error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seatspace`.`floor`, CONSTRAINT `building_id` FOREIGN KEY (`id`) REFERENCES `building` (`id`))
I want to insert, update and delete floors relating to their specified building_id. Any help would be appreciated.

I have fixed the problem by changing the constraint name for the foreign key. I also rewrote parts of the schema so all of the desired columns were present. Here is the final schema and CRUD.
CREATE TABLE `floor` (
`floor_id` int(11) NOT NULL AUTO_INCREMENT,
`number` int(11) NOT NULL,
`building_id` int(11) NOT NULL,
PRIMARY KEY (`floor_id`),
UNIQUE KEY `floor_id_UNIQUE` (`floor_id`),
KEY `building_id_idx` (`building_id`),
CONSTRAINT `building_id` FOREIGN KEY (`building_id`) REFERENCES `building`
(`building_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
INSERT INTO `floor` (floor_id, `number`, building_id) VALUES (default, 3,
(SELECT building_id FROM building WHERE building_id=2)) ;
UPDATE `floor` SET `number`=3, building_id=1 WHERE floor_id=2;
DELETE FROM `floor` WHERE floor_id=3;
CREATE TABLE `building` (
`building_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`building_id`),
UNIQUE KEY `building_id_UNIQUE` (`building_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
INSERT INTO building (building_id, name) VALUES (DEFAULT, '1 West');
UPDATE `building` SET `name`='3 West' WHERE building_id=2;
DELETE FROM `building` WHERE building_id=2;

Related

Error while inserting the recordsCannot add or update a child row: a foreign key constraint fails

I have created tables in MYSQL as follows
Author Table
CREATE TABLE `author` (
`AuthorId` varchar(25) NOT NULL,
`AuthorName` varchar(50) NOT NULL,
PRIMARY KEY (`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Books Table
CREATE TABLE `books` (
`DocId` int(11) NOT NULL,
`ISBN` varchar(13) NOT NULL,
PRIMARY KEY (`DocId`),
KEY `DocId` (`DocId`),
CONSTRAINT `books_ibfk_1` FOREIGN KEY (`DocId`) REFERENCES `document`
(`DocId`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Document Table
CREATE TABLE `document` (
`DocId` int(11) NOT NULL,
`Title` varchar(50) NOT NULL,
`PublishDate` date DEFAULT NULL,
`AuthorId` varchar(10) DEFAULT NULL,
`DocType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`DocId`),
KEY `AuthorId` (`AuthorId`),
CONSTRAINT `document_ibfk_3` FOREIGN KEY (`AuthorId`) REFERENCES `author`
(`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I made a server for my PHP website on XAMPP and am using mysql but when I try inserting the values in Document table I get
error while inserting the recordsCannot add or update a child row: a foreign
key constraint fails (`librarydb`.`document`, CONSTRAINT `document_ibfk_3`
FOREIGN KEY (`AuthorId`) REFERENCES `author` (`AuthorId`))
How do I resolve this issue?
Your linked fields author.AuthorId and document.AuthorId are not defined the same way.
From the docs:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same.
So make them both varchar(10) NOT NULL - or whatever you need.

Unable to create foreign key in PHPmyadmin

I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work

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;

Insertion Failed:Cannot add or update a child row: a foreign key constraint fails

I have two tables- users and language with a foreign key link of their primary key 'id'.
I have checked that the type is innoDB for the tables. I have delete- restrict and update -cascade.
This insert query, inserts it into the language table: (it can be more than one row which is added as the form has dynamic clickevent button)
if(empty($_SESSION['user_id'])) { // user not logged in; redirect to somewhere else }
$sql_insert = "INSERT into `language`
(`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$native','$other','$other_list','$other_read','$other_spokint','$other_spokprod',
'$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
This is the full error:
Insertion Failed:Cannot add or update a child row: a foreign key constraint fails
(`members`.`language`, CONSTRAINT `language_ibfk_1` FOREIGN KEY (`id`)
REFERENCES `users` (`id`))
Any help would be appreciated!
Table structure for table language:
CREATE TABLE IF NOT EXISTS `language` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
RELATIONS FOR TABLE `language`:
`id`
`users` -> `id`
You have to use a structure like this:
create table users (
id int not null auto_increment,
<additional fields>,
primary key (id)
) ENGINE=InnoDB;
create table language(
id int not null auto_increment,
user_id int not null,
<additional fields>,
primary key (id),
foreign key (user_id) references users(id) on delete restrict on update cascade
) ENGINE=InnoDB;

Problem creating a database with PHP PDO

I'm having a problem with a SQL query in my PHP Application. When the user access it for the first time, the app executes this query to create all the database:
CREATE TABLE `databases` (
`id` bigint(20) NOT NULL auto_increment,
`driver` varchar(45) NOT NULL,
`server` text NOT NULL,
`user` text NOT NULL,
`password` text NOT NULL,
`database` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
-- --------------------------------------------------------
--
-- Table structure for table `modules`
--
CREATE TABLE `modules` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`title` varchar(100) NOT NULL,
`type` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ;
-- --------------------------------------------------------
--
-- Table structure for table `modules_data`
--
CREATE TABLE `modules_data` (
`id` bigint(20) NOT NULL auto_increment,
`module_id` bigint(20) unsigned NOT NULL,
`key` varchar(150) NOT NULL,
`value` tinytext,
PRIMARY KEY (`id`),
KEY `fk_modules_data_modules` (`module_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=184 ;
-- --------------------------------------------------------
--
-- Table structure for table `modules_position`
--
CREATE TABLE `modules_position` (
`user_id` bigint(20) unsigned NOT NULL,
`tab_id` bigint(20) unsigned NOT NULL,
`module_id` bigint(20) unsigned NOT NULL,
`column` smallint(1) default NULL,
`line` smallint(1) default NULL,
PRIMARY KEY (`user_id`,`tab_id`,`module_id`),
KEY `fk_modules_order_users` (`user_id`),
KEY `fk_modules_order_tabs` (`tab_id`),
KEY `fk_modules_order_modules` (`module_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tabs`
--
CREATE TABLE `tabs` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`title` varchar(60) NOT NULL,
`columns` smallint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
-- --------------------------------------------------------
--
-- Table structure for table `tabs_has_modules`
--
CREATE TABLE `tabs_has_modules` (
`tab_id` bigint(20) unsigned NOT NULL,
`module_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`tab_id`,`module_id`),
KEY `fk_tabs_has_modules_tabs` (`tab_id`),
KEY `fk_tabs_has_modules_modules` (`module_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`login` varchar(60) NOT NULL,
`password` varchar(64) NOT NULL,
`email` varchar(100) NOT NULL,
`name` varchar(250) default NULL,
`user_level` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_users_user_levels` (`user_level`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
-- --------------------------------------------------------
--
-- Table structure for table `users_has_tabs`
--
CREATE TABLE `users_has_tabs` (
`user_id` bigint(20) unsigned NOT NULL,
`tab_id` bigint(20) unsigned NOT NULL,
`order` smallint(2) NOT NULL,
`columns_width` varchar(255) default NULL,
PRIMARY KEY (`user_id`,`tab_id`),
KEY `fk_users_has_tabs_users` (`user_id`),
KEY `fk_users_has_tabs_tabs` (`tab_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `user_levels`
--
CREATE TABLE `user_levels` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`level` smallint(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
--
-- Table structure for table `user_meta`
--
CREATE TABLE `user_meta` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`user_id` bigint(20) unsigned default NULL,
`key` varchar(150) NOT NULL,
`value` longtext NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_meta_users` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `modules_data`
--
ALTER TABLE `modules_data`
ADD CONSTRAINT `fk_modules_data_modules` FOREIGN KEY (`module_id`) REFERENCES `modules` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
--
-- Constraints for table `modules_position`
--
ALTER TABLE `modules_position`
ADD CONSTRAINT `fk_modules_order_modules` FOREIGN KEY (`module_id`) REFERENCES `modules` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_modules_order_tabs` FOREIGN KEY (`tab_id`) REFERENCES `tabs` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_modules_order_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
--
-- Constraints for table `users`
--
ALTER TABLE `users`
ADD CONSTRAINT `fk_users_user_levels` FOREIGN KEY (`user_level`) REFERENCES `user_levels` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `user_meta`
--
ALTER TABLE `user_meta`
ADD CONSTRAINT `fk_user_meta_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
INSERT INTO `user_levels` VALUES(1, 10);
INSERT INTO `user_levels` VALUES(2, 1);
INSERT INTO `users` VALUES(1, 'admin', 'password', 'changethis#testing.com', NULL, 1);
INSERT INTO `user_meta` VALUES (NULL, 1, 'last_tab', 1);
In some environments i get this error:
SQLSTATE[HY000]: General error: 1005
Can't create table 'dms.databases'
(errno: 150)
I tried everything that I could find on Google but nothing works.
The strange part is that if I run this query in PhpMyAdmin he creates my database, without any error.
The problem is likely to be in the constraints part of your queries.
The error 150 is mentioned in the InnoDB Documentation:
If you re-create a table that was
dropped, it must have a definition
that conforms to the foreign key
constraints referencing it. It must
have the right column names and types,
and it must have indexes on the
referenced keys, as stated earlier. If
these are not satisfied, MySQL returns
error number 1005 and refers to error
150 in the error message.
If MySQL reports an error number 1005 from a CREATE TABLE statement,
and the error message refers to error
150, table creation failed because a
foreign key constraint was not
correctly formed. Similarly, if an
ALTER TABLE fails and it refers to
error 150, that means a foreign key
definition would be incorrectly formed
for the altered table. You can use
SHOW ENGINE INNODB STATUS to display a
detailed explanation of the most
recent InnoDB foreign key error in the
server.
Source: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
It will also occur if the definitions of the references are not identical (i.e. one is signed, one is unsigned bigint) or mixing unique indexes over several columns with them.

Categories