Cannot add foreign key with WordPress wp_posts table - php

I'm trying to add a new table which has a relation with {wp_posts} table, This code is working properly in localhost and it passes all tests but it failed on server database and generates [Cannot add foreign key constraint].
The [post_id] field is exactly like {wp_posts->ID} field .. I don't know what I missed.
global $wpdb;
$charset_collate = $wpdb->collate;
$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';
dbDelta( "CREATE TABLE IF NOT EXISTS {$tbl_my_users} (
user_id BIGINT(20) UNSIGNED NOT NULL,
post_id BIGINT(20) UNSIGNED NOT NULL,
name VARCHAR(150) NOT NULL,
email TINYTEXT NULL,
INDEX (name),
PRIMARY KEY (user_id),
CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
CONSTRAINT Constr_Unique_User UNIQUE( name ),
CONSTRAINT Constr_My_Users
FOREIGN KEY FK_My_Users (post_id) REFERENCES {$wpdb->posts} (ID) ON DELETE CASCADE ON UPDATE CASCADE
) COLLATE {$charset_collate}" );

old question but i face this problem now.
the issue is when we want to set relation we need to match the column type, collation and the engine.
wp_posts ID : bigint(20) UNSIGNED
your table post_id: bigint(20) UNSIGNED
this is match, but you have problem with ENGINE.
example : the old table is written as innodb but your MYSQL default engine is set as MYISAM. so you without define ENGINE type, you will create MYISAM table instead InnoDB which not support relationship/foreign key. Note: old mysql version using MYISAM as default engine, not InnoDB
In my problem:
wp_posts ID: bigint(20) UNSIGNED InnoDB
my table post_id: bigint(20) InnoDB
the engine and type is match, but i got the eror. Because i forgot to set attribute UNSIGNED. when i set the same attribute, all works perfectly.
Note: don't forget about collation when using string type like varchar, char, etc
i hope this will help others.

try this bewlo query
global $wpdb;
$charset_collate = $wpdb->collate;
$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';
dbDelta("CREATE TABLE IF NOT EXISTS ".$tbl_my_users." (
user_id BIGINT(20) UNSIGNED NOT NULL,
post_id BIGINT(20) UNSIGNED NOT NULL,
name VARCHAR(150) NOT NULL,
email TINYTEXT NULL,
INDEX (name),
PRIMARY KEY (user_id),
CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
CONSTRAINT Constr_Unique_User UNIQUE( name ),
CONSTRAINT Constr_My_Users
FOREIGN KEY (`post_id`) REFERENCES ".$wpdb->prefix."posts (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) COLLATE SET utf8 COLLATE utf8_general_ci" );

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.

ERROR 1005 (HY000): Can't create table 'db.POSTS' (errno: 150)

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;;

Can't create foreign key in mysql (Wordpress)

I used following query to create a table, but it returns error about foreign key:
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
supervisor char(30) NOT NULL,
customer char(30) NOT NULL,
order_id int(40) NOT NULL,
status int(5) NOT NULL,
amount int(40) DEFAULT 0,
FOREIGN KEY (order_id) REFERENCES wp_post(ID),
) $charset_collate;";
Error:
20-Sep-2015 12:12:36] خطای You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ID') ON DELETE CASCADE
) DEFAULT CHARACTER SET utf8' at line 8 در پایگاه‌داده وردپرس برای دستور CREATE TABLE wp_Arvand_Marketing (
id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
supervisor char(30) NOT NULL,
customer char(30) NOT NULL,
order_id int(40) NOT NULL,
status int(5) NOT NULL,
amount int(40) DEFAULT 0,
FOREIGN KEY (order_id) REFERENCES post('ID') ON DELETE CASCADE
) DEFAULT CHARACTER SET utf8 ساخته شده توسط activate_plugin, do_action('activate_woocommerce-arvandkala/safircod.php'), call_user_func_array, adv_activate_plugins, dbDelta
You meant to use backtique around the ID column name and not single quote; which is essentially making it a string literal rather a column name.
Your foreign key line
REFERENCES post('ID') ON DELETE CASCADE
It should be
REFERENCES post(`ID`) ON DELETE CASCADE

ID auto increase but not unique

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`

#1005 - Can't create table 'database.viewers' (errno: -1)

this table is already work fine
create table posts (
id bigint(20) unsigned not null auto_increment,
title varchar(200) not null,
content text,
mdesc varchar(340),
pdate timestamp not null default current_timestamp,
lupdate timestamp not null default '0000-00-00 00:00:00',
perma varchar(120) not null,
cat_id smallint(5) unsigned not null,
user_id int(11) unsigned not null,
views int(11) unsigned not null default 0,
status tinyint(1) unsigned not null default 0,
primary key (id),
unique key (title,cat_id),
foreign key (cat_id) references category (id) on delete restrict on update cascade,
foreign key (user_id) references users (id) on delete cascade on update cascade
) engine=innodb default charset=utf8;
but i dont know why i cant query viewers table i dont know why
create table viewers (
id int(11) unsigned not null auto_increment,
post_id bigint(20) unsigned not null,
primary key (id),
foreign key (post_id) references posts (id) on delete cascade
) engine=innodb default charset=utf8;
please help :)
Please try removing fks
Most commonly it is because of different properties.
Check
if id of post table is having same properties as of this? (here bigint)
Other possibilities could be
it isn't innodb engine for other table.
Names of fks are not unique

Categories