Can not add foreign key constraint when creating new tables [duplicate] - php

This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 1 year ago.
I'am creating a very new DB and i am getting this error when i try to add some foreign key to my tables
:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Here are my codes :
$pdo->exec("CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL,
password CHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
ft_img VARCHAR(255) NOT NULL,
content text NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
role ENUM ('Author', 'Admin', 'Suscriber') NULL DEFAULT 'Suscriber',
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
//Create posts table
$pdo->exec("CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
user_id int NULL,
title VARCHAR(255) NOT NULL,
chapo VARCHAR(255) NOT NULL,
ft_img VARCHAR(255) NOT NULL,
content text NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES USERS (id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
//Create comments table
$pdo->exec("CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
pseudo VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
content text NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// Create posts_comments table
$pdo->exec("CREATE TABLE posts_comments (
post_id INT UNSIGNED NOT NULL,
comment_id INT UNSIGNED NOT NULL,
PRIMARY KEY (post_id, comment_id),
CONSTRAINT fk_post
FOREIGN KEY (post_id)
REFERENCES posts (id)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_comment
FOREIGN KEY (comment_id)
REFERENCES comments (id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
Error message : Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
I just can not figure out why i am getting this erro, if someone can help ?
Thanks in advance,

post_id INT UNSIGNED NOT NULL,
comment_id INT UNSIGNED NOT NULL,
These are INT UNSIGNED, but they are referencing primary keys that are INT.
The data types must be the same. Signed versus unsigned is enough to make them incompatible for purposes of foreign key references.
You might like this answer that I contributed to, which is a checklist of things that can go wrong with foreign keys: https://stackoverflow.com/a/4673775/20860

Related

General error: 3780 Referencing column 'post_id' and referenced column 'id' in foreign key constraint 'fk_post' are incompatible

I've been stuck on this error for several days. I can't seem to find the error to correct the problem. A charitable soul could help me plz ?
i got this error :
General error: 3780 Referencing column 'post_id' and referenced column 'id' in foreign key constraint 'fk_post' are incompatible.
<?php
require dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'vendor' .DIRECTORY_SEPARATOR . 'autoload.php';
require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'DataPDO.php';
use Config\Connection;
$pdo = new Connection();
$pdo->getPDO()->exec("CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL,
password CHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
ft_image VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
email VARCHAR(255) NOT NULL,
role ENUM ('Author', 'Admin', 'Subscriber') NULL DEFAULT 'Subscriber',
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
echo 'Created table users succesfully !';
$pdo->getPDO()->exec("CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
user_id INT DEFAULT NULL,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
ft_image VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
echo 'Created table posts succesfully !';
$pdo->getPDO()->exec("CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
pseudo VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
echo 'Created table comments succesfully !';
$pdo->getPDO()->exec("CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
ft_image VARCHAR(255) NOT NULL,
content TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
echo 'Created table categories succesfully !';
$pdo->getPDO()->exec("CREATE TABLE posts_comments (
post_id INT UNSIGNED NOT NULL,
comment_id INT UNSIGNED NOT NULL,
PRIMARY KEY (post_id, comment_id),
CONSTRAINT fk_post
FOREIGN KEY (post_id)
REFERENCES posts (id)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_comment
FOREIGN KEY (comment_id)
REFERENCES comments (id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) DEFAULT CHARSET=utf8mb4");
echo 'Created table posts_comments succesfully !';
$pdo->getPDO()->exec("CREATE TABLE users_posts (
user_id INT UNSIGNED NOT NULL,
post_id INT UNSIGNED NOT NULL,
PRIMARY KEY (user_id, post_id),
CONSTRAINT fk_user
FOREIGN KEY (user_id)
REFERENCES users (id)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_post
FOREIGN KEY (post_id)
REFERENCES posts (id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) DEFAULT CHARSET=utf8mb4");
echo 'Created table users_posts succesfully !';
$pdo->getPDO()->exec("CREATE TABLE posts_categories (
post_id INT UNSIGNED NOT NULL,
category_id INT UNSIGNED NOT NULL,
PRIMARY KEY (post_id, category_id),
CONSTRAINT fk_post
FOREIGN KEY (post_id)
REFERENCES posts (id)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_category
FOREIGN KEY (category_id)
REFERENCES categories (id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) DEFAULT CHARSET=utf8mb4");
echo 'Created table posts_categories succesfully !';
id in the table Posts is
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
post_id in posts_categories is
post_id INT UNSIGNED NOT NULL,
Here the part "unsigned" creates your problem
Make both Unsigned, or leave it out

1452 - Cannot add or update a child row

I have a problem with my Database (using MariaDB) to insert a new row
I Having the following errors
Cannot add or update a child row: a foreign key constraint fails
(DbName_boutique.Commande, CONSTRAINT bdc_managed_by___fk FOREIGN
KEY (bdc_managed_by_user_id) REFERENCES utilisateur
(utilisateur_id))INSERT INTO Commande (lien_devis, lien_bdc,
end_devis, bdc_status, devis_created_by_user_id,
bdc_managed_by_user_id, entreprise_id)
I have this code on my controller :
$unknow = NULL;
$end_date = date('d/m/Y', strtotime("+1 month"));
$user = checkConnected($bdd);
Commande::create($bdd, $new_full_modele_devis_path, $new_full_modele_devis_path, $end_date, 0, $user->getId(), $user->getId(), $entreprise->getId());
The $unknow are values I used later in an another Controller.
My Table "Commande" is built like following :
create table dBName.Commande
(
commande_id int not null
primary key,
lien_devis varchar(255) null,
lien_bdc varchar(255) null,
end_devis datetime null,
bdc_status int null,
devis_created_by_user_id mediumint unsigned null,
bdc_managed_by_user_id mediumint unsigned null,
entreprise_id smallint(5) unsigned null,
constraint bdc_managed_by___fk
foreign key (bdc_managed_by_user_id) references dBName.utilisateur (utilisateur_id),
constraint devis_created_by___fk
foreign key (devis_created_by_user_id) references dBName.utilisateur (utilisateur_id),
constraint entreprise___fk
foreign key (entreprise_id) references dBName.entreprise (entreprise_id)
);
And I have later the user table :
create table dBName.utilisateur
(
utilisateur_id mediumint unsigned auto_increment
primary key,
utilisateur_password varchar(255) null,
utilisateur_nom varchar(50) null,
utilisateur_prenom varchar(50) null,
utilisateur_email varchar(255) null,
utilisateur_telephone varchar(10) null,
utilisateur_fax varchar(25) null,
is_active tinyint(1) null
)
charset = utf8mb4;
And entreprise :
create table dBName.entreprise
(
entreprise_id smallint(5) unsigned auto_increment
primary key,
entreprise_nom varchar(100) null,
entreprise_siret char(14) null,
entreprise_telephone char(10) null,
entreprise_salesforce_number varchar(100) null,
entreprise_compte_client varchar(100) null,
entreprise_raison_sociale varchar(100) null,
entreprise_APE varchar(25) null,
entreprise_image_link varchar(255) null,
adresse_id mediumint unsigned null,
constraint FK_entreprise_adresse_id
foreign key (adresse_id) references dBName.adresse (adresse_id)
)
charset = utf8mb4;
I don't understand Why i'm Habing the error... And bit of help could help me a lot.. Thank you.
In Commande table, the column bdc_managed_by_user_id is mapped to utilisateur_id column of utilisateur table via foreign key reference.
This means, whenever you insert a row in Commande table, corresponding bdc_managed_by_user_id has to be one of the utilisateur_id present in utilisateur table. If not, you will get the above error.
This is called Foreign Key Constraint and you can have a look at this example describing how it works.

Error #sql-890_730 when creating constraint in MySQL

This is my t_complaint
CREATE TABLE `t_complaint` (
`idcomplaint` int(11) NOT NULL,
`tglterima` date DEFAULT NULL,
`dept` varchar(5) DEFAULT NULL,
`pengirim` varchar(255) DEFAULT NULL,
`kontak` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`telp` varchar(255) DEFAULT NULL,
`jenis` varchar(45) DEFAULT NULL,
`uraian` text,
`uniqueid` varchar(9) DEFAULT NULL,
`responder` varchar(245) DEFAULT NULL,
`tgljawab` date DEFAULT NULL,
`jawaban` text,
`status` varchar(45) DEFAULT NULL,
`tglclose` date DEFAULT NULL,
`createddate` datetime DEFAULT NULL,
`createdby` varchar(45) DEFAULT NULL,
`modifieddate` datetime DEFAULT NULL,
`modifiedby` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and this is t_complaint_detail:
CREATE TABLE `t_complaint_detail` (
`no` int(11) NOT NULL,
`uniqueid` varchar(9) DEFAULT NULL,
`uploader` varchar(100) DEFAULT NULL,
`st_uploader` int(11) DEFAULT NULL,
`file_upload` text,
`original_name` text,
`status` int(11) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
t_complaint.idcomplaint is a primary key with Auto Increment attribute
t_complaint_detail.no is a primary key with Auto Increment attribute
I'd like to connected these table via uniqueid
I've tried ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('uniqueid') REFERENCES t_complaint('uniqueid')
The query above gives error. The error is #1005 - Can't create tablebsm.#sql-890_730(errno: 150 "Foreign key constraint is incorrectly formed") (Details…)
bsm in the error is my database (my database is bsm)
Foreign key should must be a primary key in parent table. The question is, why you are adding a redundant 'uniqueId' in both the table? You can simply define a foreign key constraint like this :
t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('idcomplaint') REFERENCES t_complaint('idcomplaint').
It should work.
Error came like this
ERROR 1215 (HY000): Cannot add foreign key constraint
Because you need to create primary key in table.you can add primary key
like this
alter table t_complaint_detail modify uniqueid varchar(20) not null;
and
alter table t_complaint_detail modify uniqueid varchar(20) not null;
after it will be works
ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY (uniqueid) REFERENCES t_complaint(uniqueid);
please read here for more reference that will be help
It's working fine for me :
Try this :
ALTER TABLE t_complaint ADD CONSTRAINT t_complaint_detail
FOREIGN KEY ( uniqueid ) REFERENCES t_complaint( uniqueid )
Reference here :
https://www.w3schools.com/sql/sql_foreignkey.asp

Yii2-Integrity constraint violation – yii\db\IntegrityException

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
The SQL being executed was: INSERT INTO `employee` (`client_code`, `company_name`, `emp_email`, `emp_mobile`, `emp_first_name`, `emp_last_name`) VALUES ('12345678', 'PVPPCOE', 'saurabhkulkarni2010#hotmail.com', '+449029792183', 'Saurabh', 'Kulkarni')
Error Info: Array
(
[0] => 23000
[1] => 1452
[2] => Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
)
I have three tables Client, Employee and create_client, out of which client and employee has two foreign keys.
This problem is showing when I try to insert data from create_client to employee which has exact same field.
What should I do so that I can insert two tables at one i.e create_client and employee
UPDATE-
Table Structure
1)client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
2)create_client
CREATE TABLE IF NOT EXISTS `create_client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
3)employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
This is my table structure, first user will create client that means first it will update create_client. Now if user wants he can add many employee under one client code now user will update employee table from Yii2 dynamic form widget.
For using this widget I have created one table call client this will store only client_code and company name remaining data will go in employee table e.g emp_mobile,emp_email, emp_first_name, emp_last_name.
Now this problem is pop up when user first enters data into create_client table.
everything is working between client and employee table user able to enter as many employee as it wants using Yii2 dynamic form Widget but not working for create_client
Apparently you also have a foreign key in the employee table referencing the client_code of the client table, so you can only use client_code values that already exist in the client table.
I don't know what the structure of the create_client table looks like and what its purpose is, but based on your info I assume that you should first insert the data in client, then in employee and finally in create_client, so that every foreign key's value exists in its respective table.
If this is not correct, please post your table structures and the data or queries that could be causing this.
Edit after your comment: I assume that your table structure looks like this:
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `create_client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
However, I would suggest to use client as the parent table and move the foreign key constraint to create_client, so that both employee and create_client have a foreign key of client. I would also like to normalise this and get rid of company_name in the child tables:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`),
CONSTRAINT `create_client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
The next improvement would be to use the employee table for both unique and non-unique client_code inserts. Instead of using 2 identical tables, apart from the unique key, you could do the unique validation in Yii instead of in MySQL. You can specify the table name in the tableName() method of the CreateClient model . This will remain:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This should allow you to use the dynamic form, with Client as the main model and Employee as the items model.
On Yii2 using IO Generator (Model) and MySQL I have found the following.
I have seen SET '' instead of SET NULL in update SQL statement(s) on field(s) with foreign key constraints that have caused a "Integrity constraint violation".
My "fix" is to add a default rule on the foreign key field in the model, like so:
public function rules()
{
return [
//
// your other rules
//
[['field_name_with_foreign_key'], 'default', 'value' => null],
];
}
Hope this helps someone.
remove all foreign key checks and simplify database.
the problem lies in your foreign key structure.
learn carefully about primary keys and foreign keys.
make new database again without foreign keys then check.

#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