syntax error foreign keys - php

I'm new to php/sql and i'm getting a syntax error on the line with the foreign key.
Syntax error or access violation: 1064
$createQuery ="CREATE TABLE AthleteTable
(
athleteID INT(6) NOT NULL AUTO_INCREMENT,
lastName VARCHAR(20) NOT NULL,
firstName VARCHAR(30) NOT NULL,
gender CHAR(1) NOT NULL,
image VARCHAR(20) NOT NULL,
eventID INT(6) NOT NULL,
medal VARCHAR(6) NOT NULL,
CONSTRAINT foreign FOREIGN KEY (eventID) REFERENCES eventsTable(eventID),
PRIMARY KEY(athleteID)
)";
If any one knows what is wrong would appreciate some help.
------------>
new error:
inserting data AthleteTable failed SQLSTATE[23000]: Integrity
constraint violation: 1452 Cannot add or update a child row: a foreign
key constraint fails (powlz1_in612.AthleteTable, CONSTRAINT
AthleteTable_ibfk_1 FOREIGN KEY (eventID) REFERENCES eventsTable
(eventID))
here is where I make the tables:
$createQuery ="CREATE TABLE eventsTable
(
eventID INT(6) NOT NULL AUTO_INCREMENT,
sport VARCHAR(20) NOT NULL,
event VARCHAR(30) NOT NULL,
PRIMARY KEY (eventID)
)";
$pdo->exec($createQuery);
$createQuery ="CREATE TABLE AthleteTable
(
athleteID INT(6) NOT NULL AUTO_INCREMENT,
firstName VARCHAR(20) NOT NULL,
lastName VARCHAR(20) NOT NULL,
gender VARCHAR(20) NOT NULL,
image VARCHAR(20) NOT NULL,
eventID INT(20) NOT NULL,
medal VARCHAR(6) NOT NULL,
CONSTRAINT SportEvents FOREIGN KEY (`eventID`) REFERENCES eventsTable(`eventID`),
PRIMARY KEY(`athleteID`)
)";
$pdo->exec($createQuery);
after looking at others questions it all seems to be a missing field, but both tables include an eventID so I don't get why it is failing?

$createQuery ="CREATE TABLE AthleteTable
(
athleteID INT(6) NOT NULL AUTO_INCREMENT,
lastName VARCHAR(20) NOT NULL,
firstName VARCHAR(30) NOT NULL,
gender CHAR(1) NOT NULL,
image VARCHAR(20) NOT NULL,
eventID INT(6) NOT NULL,
medal VARCHAR(6) NOT NULL,
CONSTRAINT FOREIGN KEY (eventID) REFERENCES eventsTable(eventID),
PRIMARY KEY(athleteID)
)";
You had the word FOREIGN twice. That solved your 1064.
Read comments below about your 1452 error that would follow due to setup issues on your referenced table.

Related

(errno: 150 "Foreign key constraint is incorrectly formed") i have no idea what is this

CREATE TABLE files
(file_id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
path VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL,
branch INT(5) NOT NULL,
sem INT(5) NOT NULL,
subject INT(5) NOT NULL,
uploader_id INT(11),
FOREIGN KEY (uploader_id) REFERENCES users(user_id) );
Because user_id and uploader_id column data types are not same
i.e. user_id is BIGINT(20) and uploder_id is INT(11) then there is an error for incorrectly formed error
maybe it will helpful

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 with mysql relation foreign key

I try to relate tables mysql but I have this error
Error Code: 1215. Cannot add foreign key constraint
this is the mysql script
CREATE DATABASE prototipo;
USE prototipo;
CREATE TABLE tb_tipo_usuario(
id int not null,
tipo varchar(30) not null,
constraint PK_tb_tipo_usuario_id primary key(id)
);
CREATE TABLE tb_usuarios(
id_usuario int(5) zerofill not null auto_increment,
usuario varchar(30) not null,
clave varchar(30) not null,
nombre varchar(30) not null,
apellido varchar(30) not null,
cedula varchar(30) not null,
cargo varchar(40) not null,
tipo_usuario int not null,
fecha_registro date not null,
constraint PK_tb_usuarios_id_usuario primary key(id_usuario),
constraint fk_tb_usuarios_tipo_usuario foreign key(tipo_usuario) references tb_tipo_usuario(id)
);
CREATE TABLE tb_tipo_pollo(
id_tipo_pollo int(2) zerofill not null auto_increment,
tipo_pollo varchar(30) not null,
constraint pk_tb_tipo_pollo_id_tipo_pollo primary key(id_tipo_pollo)
);
create table tb_parvada(
id_parvada int(5) zerofill not null,
cantidad int not null,
constraint pk_tb_parvada_id_parvada primary key(id_parvada)
);
create table tb_entrada_parvada(
id_entrada_parvada int(5) zerofill not null auto_increment,
tipo_pollo int not null,
cantidad int not null,
fecha_entrada date not null,
fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
comentario varchar(500) null,
id_usuario int not null,
constraint pk_tb_entrada_parvada_id_entrada_pollo primary key(id_entrada_parvada),
constraint fk_tb_entrada_parvada_tipo_pollo foreign key(tipo_pollo) references tb_tipo_pollo(id_tipo_pollo),
constraint fk_tb_entrada_parvada_id_entrada_parvada foreign key(id_entrada_parvada) references tb_parvada(id_parvada),
constraint fk_tb_entrada_parvada_id_usuario foreign key(id_usuario) references tb_usuarios(id_usuario)
);
create table tb_muerte_pollo(
id_muerte int(5) zerofill not null auto_increment,
id_parvada int not null,
cantidad int not null,
fecha date,
fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
motivo varchar(300),
id_usuario int not null,
constraint pk_tb_muerte_pollo primary key(id_muerte),
constraint fk_tb_muerte_pollo foreign key(id_parvada) references tb_parvada(id_parvada),
constraint fk_tb_muerte_pollo_id_usuario foreign key(id_usuario) references tb_usuarios(id_usuario)
);
The error is when I try add the table tb_entrada_parvada or the table tb_muerte_pollo I don't know how repair this error, just work when I delete the foreign key
The DataType and attributes of the column in the reference table should be same as the current table. You are missing ZeroFill for many columns. That why you are getting the error. Kindly Change it.
create table tb_entrada_parvada(
id_entrada_parvada int(5) zerofill not null auto_increment,
tipo_pollo int(2) zerofill not null,
cantidad int not null,
fecha_entrada date not null,
fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
comentario varchar(500) null,
id_usuario int(5) zerofill not null,
constraint pk_tb_entrada_parvada_id_entrada_pollo primary key(id_entrada_parvada),
constraint fk_tb_entrada_parvada_tipo_pollo foreign key(tipo_pollo) references tb_tipo_pollo(id_tipo_pollo),
constraint fk_tb_entrada_parvada_id_entrada_parvada foreign key(id_entrada_parvada) references tb_parvada(id_parvada),
constraint fk_tb_entrada_parvada_id_usuario foreign key(id_usuario) references tb_usuarios(id_usuario)
);
create table tb_muerte_pollo(
id_muerte int(5) zerofill not null auto_increment,
id_parvada int zerofill not null,
cantidad int not null,
fecha date,
fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
motivo varchar(300),
id_usuario int zerofill not null,
constraint pk_tb_muerte_pollo primary key(id_muerte),
constraint fk_tb_muerte_pollo foreign key(id_parvada) references tb_parvada(id_parvada),
constraint fk_tb_muerte_pollo_id_usuario foreign key(id_usuario) references tb_usuarios(id_usuario)
);
DEMO FIDDLE

"Key column 'username' doesn't exist in table"

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.

Problem in Saving Multi Level Models in YII

My Table structure for user and his adress detail is as follows
CREATE TABLE tbl_users (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
loginname varchar(128) NOT NULL,
enabled enum("True","False"),
approved enum("True","False"),
password varchar(128) NOT NULL,
email varchar(128) NOT NULL,
role_id int(20) NOT NULL DEFAULT '2',
name varchar(70) NOT NULL,
co_type enum("S/O","D/O","W/O") DEFAULT "S/O",
co_name varchar(70),
gender enum("MALE","FEMALE","OTHER") DEFAULT "MALE",
dob date DEFAULT NULL,
maritalstatus enum("SINGLE","MARRIED","DIVORCED","WIDOWER") DEFAULT "MARRIED",
occupation varchar(100) DEFAULT NULL,
occupationtype_id int(20) DEFAULT NULL,
occupationindustry_id int(20) DEFAULT NULL,
contact_id bigint(20) unsigned DEFAULT NULL,
signupreason varchar(500),
PRIMARY KEY (id),
UNIQUE KEY loginname (loginname),
UNIQUE KEY email (email),
FOREIGN KEY (role_id) REFERENCES tbl_roles (id),
FOREIGN KEY (occupationtype_id) REFERENCES tbl_occupationtypes (id),
FOREIGN KEY (occupationindustry_id) REFERENCES tbl_occupationindustries (id),
FOREIGN KEY (contact_id) REFERENCES tbl_contacts (id)
) ENGINE=InnoDB;
CREATE TABLE tbl_contacts (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
contact_type enum("cres","pres","coff"),
address varchar(300) DEFAULT NULL,
landmark varchar(100) DEFAULT NULL,
district_id int(11) DEFAULT NULL,
city_id int(20) DEFAULT NULL,
state_id int(20) DEFAULT NULL,
pin_id bigint(20) unsigned DEFAULT NULL,
area_id bigint(20) unsigned DEFAULT NULL,
po_id bigint(20) unsigned DEFAULT NULL,
phone1 varchar(20) DEFAULT NULL,
phone2 varchar(20) DEFAULT NULL,
mobile1 varchar(20) DEFAULT NULL,
mobile2 varchar(20) DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (district_id) REFERENCES tbl_districts (id),
FOREIGN KEY (city_id) REFERENCES tbl_cities (id),
FOREIGN KEY (state_id) REFERENCES tbl_states (id)
) ENGINE=InnoDB;
CREATE TABLE tbl_states (
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE tbl_districts (
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
state_id int(20) DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (state_id) REFERENCES tbl_states (id)
) ENGINE=InnoDB;
CREATE TABLE tbl_cities (
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
district_id int(20) DEFAULT NULL,
state_id int(20) DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (district_id) REFERENCES tbl_districts (id),
FOREIGN KEY (state_id) REFERENCES tbl_states (id)
) ENGINE=InnoDB;
The relationship is as follows
User has multiple contacts i.e Permanent Address, Current Address, Office Address.
Each Contact has state and City.
User->Contact->state like this
How to save models of this structure in one go.
Please provide a reply ASAP
I believe I had a similar issue saving a multi leveled model with many foreign keys. It doesn't seem that it can easily be saved in 'one go'...
Take a look at my solution here
You might have a look at gii-templates extension on google code -
gii templates on google code
->> It might be documented better, but it attempts to do what you need.
(It might save you some time if you implement it well, but I'd even consider hand-coding it
if I were you.)

Categories