I have read and searched all the site, but nothing I had found worked for me...so please help a newbie understand what he is doing wrong.
So I am trying to create an add to favorite function.
I need to create 3 tables. The first two worked like magic, but the 3rd one ...well I got in the trouble with the FOREIGN KEY
I get no error message, but it won't create the 3rd table.
Here are my codes:
<?php
$connect = mysql_connect("127.0.0.1","root","");
$db = mysql_select_db("mydb");
mysql_query("CREATE TABLE IF NOT EXISTS users
(
userid bigint,
firstname varchar(25),
lastname varchar(15),
email varchar(250),
gender varchar(10),
username varchar(15),
password varchar(15),
age int,
activ boolean,
date TIMESTAMP NULL default CURRENT_TIMESTAMP
)ENGINE=INNODB
");
mysql_query("CREATE TABLE IF NOT EXISTS products (
productid int(11) NOT NULL AUTO_INCREMENT,
productname varchar(100) NOT NULL,
productdescription varchar(250) NOT NULL,
price decimal(6,2) NOT NULL,
PRIMARY KEY (`productid`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ");
mysql_query("CREATE TABLE IF NOT EXISTS favorites
(
userid bigint NOT NULL,
productid int(11) NOT NULL,
PRIMARY KEY (userid, productid),
FOREIGN KEY (userid) REFERENCES user (userid) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (productid) REFERENCES product (productid) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=INNODB
");
echo "The DataBase was successfully created!";
mysql_close();
?>
The foreign keys refer to non-existing tables.
The tables are names users and products while the third table refers to them as user and product (singular).
"userid" of "user" table must be primary key.
Related
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id)
)
I get an error
You have an error in your SQL syntax; it seems the error is around: '
entity_id INT(10), PRIMARY KEY (id), FOREIGN KEY (entity_id) )' at
line 3
I am unable to understand on how to fix it.
Whereas when I add this
CREATE TABLE `Image` (
`Id [PK]` int (10) ,
`EntityType` varchar(32),
`EntityId [FK]` int(10)
);
the above code fixes the error
Below is the code which gives Foreign key constraints even after I tried creating image and category table first and then adding relation to it in the User Table
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) )';
if ($db->database->createTable($sql_image)) { echo "Image Table Created Successfully"; }
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully"; }
$sql_user = 'Create TABLE IF NOT EXISTS user(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10),
status boolean,
user_profile_photo int(10),
FOREIGN KEY (user_profile_photo) references image(entity_id),
FOREIGN KEY (category) references category(entity_id) );';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully"; }
If you want a foreign key to be added then you need to define the reference table means in which table the entity_id belongs
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id) REFERENCES Entity(entity_id)
)
The last line it's wrong.
Try something like this:
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)'
FOREIGN KEY (product_category, product_id)
REFERENCES second_table(category, id)
2 errors that I can see
1) 'MySQL requires indexes on foreign keys and referenced keys'. MySQL will create keys on the referencing table(users) if you do not but you have to create them on the referenced tables on entity_id(image,category)
2) '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'
see https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
This syntaxs and generates the tables (you need to decide what kind of key k1 and k2 should be):-
drop table if exists us;
drop table if exists i;
drop table if exists c;
CREATE TABLE IF NOT EXISTS i (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table i
add key k1(entity_id);
CREATE TABLE IF NOT EXISTS c (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table c
add key k2(entity_id);
Create TABLE IF NOT EXISTS us(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) unsigned,
status boolean,
user_profile_photo int(10) unsigned,
FOREIGN KEY fk1(user_profile_photo) references i(entity_id),
FOREIGN KEY (category) references c(entity_id)
);
Verify that both table columns are defined with same data type.
Verify that both table and their columns have same collation charset should be same e.g. utf-8
Even if tables have same collation , columns still could have different one.
Verify that both columns have the same signing definition. If the referencing column is int(10) unsigned so should be the referencing
column.
In my case
column user_profile_photo from user table and id from image table were having different signing definition. hence it was not adding foreign key.
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
)';
if ($db->database->createTable($sql_image)) {
echo "Image Table Created Successfully<br><br>";
}
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully<br><br>";
}
$sql_user = 'CREATE TABLE IF NOT EXISTS user(
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) UNSIGNED NOT NULL, //int(10) UNSIGNED should be match id from category table.
status boolean,
user_profile_photo int(10) UNSIGNED NOT NULL,
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
);';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully<br><br>";
}
Hi I'm having issues creating my post database. I'm trying to make a forenge key to link to my users database. Can someone please help?
Here's the code for my tables :
CREATE TABLE USERS(
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;
Here's the last InnoDB error message:
Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
There really should not be a good reason to have a compound primary key on the first table. So, I think you intend:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID),
UNIQUE (UserName)
);
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);
Some notes:
An auto-incremented id is unique on every row. It makes a good primary key.
A primary key can consist of multiple columns (called a composite primary key). However, an auto-incremented id doesn't make much sense as one of the columns. Just use such an id itself.
If you use a composite primary key, then the foreign key references need to include all columns.
I chose UserId for the foreign key reference. You could also use UserName (because it is unique).
UserName is a bad choice for foreign keys, because -- conceivably -- a user could change his or her name.
The error is caused by incorrect foreign key definition. In the concrete case you are missing a complete column in your foreign key definition.
In the USERS table you have defined primary key as composite key of UserID and UserName columns.
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID,UserName)
) ENGINE=InnoDB;
note that it is good practice to respect case of the identifiers (column names)
In the POSTS table you declared your foreign key to reference only one column in the USERS table, the UserName column. This is incorrect as you need to reference entire primary key of the USERS table which is (UserID, UserName). So to fix the error you need to add one additional column to the POSTS table and change your foreign key definition like this:
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
authorId int,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(authorId, postAuthor) REFERENCES USERS(UserID, UserName)
) ENGINE=InnoDB;
Please look at following fiddle: http://sqlfiddle.com/#!9/92ff1/1
NOTE: If you can you should re-architect this to not use the composite primary key in the USERS table as it does not make sense from what I can see in the displayed code. You can change the tables like this:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID)
) ENGINE=InnoDB;
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthorID int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthorID) REFERENCES USERS(UserID)
) ENGINE=InnoDB;;
I have a table that I want to have an id that will auto increase itself but not be primary or unique.
Is this possible?
You should really create another table, in that case.
E.g.
CREATE TABLE `Calls` (
`Id` INT(10) AUTO_INCREMENT,
`From` VARCHAR(100) NOT NULL,
`To` VARCHAR(100) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB;
CREATE TABLE `CallHistory` (
`Id` INT(15) AUTO_INCREMENT,
`CallId` INT(10) NOT NULL,
`Text` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Id`),
KEY `CallHistory_Calls_idx` (`CallId`),
CONSTRAINT `CallHistory_Calls`
FOREIGN KEY (`CallId`)
REFERENCES `calls` (`Id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
Here's a demo on SQLFiddle.
A benefit of this is that if you delete a row from Calls, the rows in CallHistory will also be deleted.
Running this query:
SELECT `Calls`.`Id`,
`Calls`.`From`,
`Calls`.`To`,
`CallHistory`.`Text`
FROM `Calls`, `CallHistory`
WHERE `Calls`.`Id` = `CallHistory`.`CallId`;
Gives results something like this:
This should work:
id int NOT NULL AUTO_INCREMENT
Anyway I don't see how it wouldn't stay unique unless you update existing values later
Yes, you need to set auto_increment constraint:
CREATE TABLE `test` (
`testID` int(11) NOT NULL, //primary key here
`testInc` int(11) NOT NULL AUTO_INCREMENT, //here is your non-primary auto increment column
PRIMARY KEY (`testID`),
KEY `testInc` (`testInc`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
and if you want this to be unique also then you may add unique constraint:
ALTER TABLE `test` ADD CONSTRAINT ux_unique_constraint UNIQUE `testInc`
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;
hey guys, i'm getting this error.
Error 1452 : Cannot add or update a child row: a foreign key constraint fails (`s2794971db/ProfileInterests`, CONSTRAINT `ProfileInterests_ibfk_2` FOREIGN KEY (`InterestID`) REFERENCES `Interests` (`ID`))
I change my tables from myISAM to innodb...found out I needed to so that delete was easier.
I had issues with it so I deleted the table which I needed to create the relationships with.
Then I made it again
I originally had
create table if not exists Users (
ID int not null auto_increment primary key,
FirstName varchar(40) not null,
LastName varchar(40) not null,
UserName varchar(40) not null,
UserEmail varchar(40) not null,
UserDOB timestamp not null,
UserJoin datetime not null
);
create table if not exists Interests(
ID int not null auto_increment primary key,
Interests varchar(40) not null
);
create table if not exists ProfileInterests (
userID int not null References Users(ID),
InterestID int not null References Interests(ID),
MiddleID int not null auto_increment primary key
);
but then I deleted the last table and made it
create table if not exists ProfileInterests (
userID int not null,
InterestID int not null,
MiddleID int not null auto_increment primary key
);
and then I made userID and InterestID into index's and then I added a relation User-> ID for userID and interests->ID for interestID
the error occurs when i'm trying to input data into via a php form.
Any ideas...really need some help!
Obviously, you're trying to insert a record into ProfileInterests for which there is no matching record in the Interests table. Look at the exact insert query, and check that you're supplying a valid value for every field in the table which is part of a foreign key relationship.