I am trying to create a Wordpress plugin. The code for setting up the database tables will be provided shortly. However the problem I'm facing is not not an error as much as a lack thereof. No matter what I do, dbdelta seems to do absolutely nothing - and wordpress will not generate any relevant error to at least give me a clue on what's going wrong.
The code is:
function create_tables()
{
global $wpdb;
$pl_nm = VSystem::$plugin_name;
$create_voters = "create table if not exists {$wpdb->prefix}{$pl_nm}_voters(
ID bigint(20) unsigned auto_increment,
user_id bigint(20) unsigned not null,
primary key (ID),
foreign key (user_id) references {$wpdb->prefix}users(ID)
);";
$create_links = "create table if not exists {$wpdb->prefix}{$pl_nm}_links(
ID bigint(20) unsigned auto_increment,
product bigint(20) unsigned,
name varchar(256) not null,
url varchar(512) not null,
description text,
posted datetime,
poster bigint(20) unsigned not null,
primary key (ID),
foreign key (poster) references {$wpdb->prefix}users(ID)
);";
$create_votes = "create table if not exists {$wpdb->prefix}{$pl_nm}_votes(
ID bigint(20) unsigned auto_increment,
link_id bigint(20) unsigned not null,
voter_id bigint(20) unsigned not null,
choice int not null,
primary key (ID),
foreign key (link_id) references {$wpdb->prefix}{$pl_nm}_links(ID),
foreign key (voter_id) references {$wpdb->prefix}users(ID)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $create_voters );
dbDelta( $create_links );
dbDelta( $create_votes );
dbDelta("asdasdsadsad");
//wp_die("{$wpdb->prefix}{$pl_nm}");
add_option('db_version', VSystem::$defaults['db_version']);
}
function vsystem_install()
{
create_tables();
}
Now I know this function is being called at least because uncommenting the wp_die command acts as it is supposed to. Can I get any help?
dbDelta("asdasdsadsad");
Not even that seems to generate any kind of response. I might be able to do this on my own if someone could tell me how to get dbdelta to do anything.
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>";
}
I have an issue that I can't figure out for the life of me. I have been creating an application in PHP/MySQL on windows using XAMPP but now I am trying to test it on a Linux based LAMP server and I get the following error when trying to create a table with foreign key constraints:
"3 - photoProjectItem table creation: Cannot add foreign key constraint"
When I run the code on XAMPP in Windows it works fine, but not within Linux. These are the tables I am trying to create:
CREATE TABLE IF NOT EXISTS generalSecurity(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
firstname VARCHAR(100) NOT NULL,
secondname VARCHAR(100) NOT NULL,
accessLevel ENUM('admin', 'contributer', 'subscriber') NOT NULL,
Email VARCHAR (200) UNIQUE NOT NULL
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS generalSiteInfo (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
siteName VARCHAR(100) NOT NULL,
siteOwnerID INT(10) UNSIGNED NOT NULL,
INDEX par_id4(siteOwnerID),
FOREIGN KEY(siteOwnerID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
siteEmail VARCHAR(100) NOT NULL,
siteAbout VARCHAR(9999) NOT NULL,
currentTheme VARCHAR(1000) NOT NULL,
siteCreateDate TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Project (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
projectAuthorID INT(10) UNSIGNED NOT NULL,
INDEX par_id(projectAuthorID),
FOREIGN KEY(projectAuthorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectName VARCHAR(100) NOT NULL,
projectBlurb VARCHAR(5000) NULL,
projectTheme VARCHAR(100) NOT NULL,
projectDate TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS ProjectItem (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
authorID INT(10) UNSIGNED NOT NULL,
INDEX par_id2(authorID),
FOREIGN KEY(authorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectID INT(10) UNSIGNED NOT NULL,
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
itemType ENUM('image', 'text') NOT NULL,
photoFileName VARCHAR(100) NULL,
itemName VARCHAR(1000) NOT NULL,
entry VARCHAR(5000) NULL,
photoMeta VARCHAR(5000) NOT NULL,
date TIMESTAMP,
deleted BOOLEAN NOT NULL
) ENGINE=INNODB;
it fails when trying to create table "ProjectItem". Can you guys see anything I am missing?
I really appreciate any help that can be given
---edit---
it works when I remove the lines
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
but I can't see any obvious issues with the relationship
The issue was that apparantly MYSQL in Linux is case sensitive whereas in Windows it doesn't appear to be. I was trying to create a relationship for the table "project" when it is called "Project"
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 am creating three tables and when trying to tie the primary and foreign keys I am receiving the error message "Key column 'username' doesn't exist in table".
Could someone take a look at my code and tell me what I am doing wrong? I have tried dropping the database and revamped the tables a few times but I am still getting the same message. Here is my code, thank you in advance for any help!
create database testproject
use testproject
create table caller_info
(
caller_id int(11) unsigned auto_increment primary key not null,
first_name varchar(35) not null,
Last_name varchar(35) not null,
phone_number int(25) not null
);
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) primary key not null
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
PRIMARY KEY(call_escalation_id),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record(username)
);
As pointed out, your table caller_escalation needs a column called username in order to create the foreign key.
It sounds like once you've added that, you're now getting a Cannot add foreign key constraint error from MySQL. The first thing that comes to mind with this kind of error is that you're using the wrong engine for your tables. You are most likely using MyISAM which does not support foreign key references - in order to use these, you will need to change the engine on all of your tables to InnoDB.
try this:
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) not null,
PRIMARY KEY (username)
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
username varchar(25) not null,
PRIMARY KEY(call_escalation_id,username),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record
);
The table caller_escalation also needs a column username, which is not there
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) unsigned not null, ;; <--- added unsigned type here
PRIMARY KEY(call_escalation_id),
username varchar(25) not null, ;; <--- added field here
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY (username) REFERENCES caller_call_record (username)
);
Also ensure the column data types are the same in both tables. You have "caller_id int(11) unsigned" in caller_info and "caller_id int(11)" in caller_escalation. I added the unsigned specifier above to make it work.
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