I have two tables main_jobs and sub_jobs with the structures below:
$query="create table if not exists main_jobs (
id int not null auto_increment, primary key(id),
industry int(3),
company_name varchar(255),
job_title varchar(255),
email varchar(255),
website varchar(255),
introduction text not null,
application_details text,
advert_date date,
expiry_date date,
upload_date date,
no_deadline int(1) default 0,
logo varchar(255),
featured varchar(20),
source varchar(10) default 'admin',
email_status int default 0,
views int(11) default 1,
short_url varchar(100),
tags varchar(255),
FOREIGN KEY (industry) REFERENCES industry (id))";
if(mysql_query($query,$link)){echo "main_jobs created<br>";} else{ die(mysql_error()); }
$query="create table if not exists sub_jobs (
id int not null auto_increment, primary key(id),
parent_id int(11) not null, FOREIGN KEY (parent_id) REFERENCES main_jobs (id),
title varchar(255),
description text not null,
category int (3), FOREIGN KEY (category) REFERENCES category (id),
job_type varchar(20),
job_level varchar(50),
min_qualification varchar(50),
min_experience int(3),
max_experience int(3),
min_salary int(11),
max_salary int(11),
show_salary int(1) default 1,
denomination varchar(10),
views int(11) default 1,
short_url varchar(100),
email varchar(255),
website varchar(255))";
if(mysql_query($query,$link)){echo "sub_jobs created<br>";} else{ die(mysql_error()); }
I want to insert records but it shows up this error:
Cannot add or update a child row: a foreign key constraint fails (`myjobmag_db`.`sub_jobs`, CONSTRAINT `sub_jobs_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `main_jobs` (`id`))
These are mysql queries and have been staring at them for hours but cannot identify the problem:
Insert into main_jobs (Runs successfully)
$resultobj=otherquery("insert into main_jobs(industry, company_name, job_title, email, website, introduction, application_details, advert_date, expiry_date, upload_date, no_deadline, logo) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "ssssssssssss", array($industry, $company_name, $job_name, $email, $website, $profile, $application, $advert_date, $expiry_date, $date_uploaded, $no_deadline, $logo));
I pick the id of the last insert (confirms that it exists in main_jobs table, this is do manually because of the error) and run insert into sub_jobs
$parent= $resultobj['obj']->insert_id;
mysql_query("insert into sub_jobs(id, parent_id, title, description, category, job_type, job_level, min_qualification, min_experience, max_experience, min_salary, max_salary, show_salary, denomination, email, website) values('', $parent, '$subtitle', '$description', '$category', '$type', '$level', '$min_qualification', '$min_experience', '$max_experience', '$min_salary', '$max_salary', '$show_salary', '$denomination', '$sub_email', '$sub_website')", $link) or die(mysql_error($link));
In my last test the id in main_jobs table is 2616 and it actually exists, yet i get an error.
Kindly assist!
Related
following is a trigger which I created in MySQL Workbench and the related tables are below as well. the trigger works perfectly in workbench but when I try to created the same trigger in phpMyAdmin, it gives me the follow error
Error
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem
ERROR: Unknown Punctuation String # 11
STR: //
SQL: delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on,
modified_from) SELECT user_id, first_name, last_name, contact_no,
user_type, email, password, active, modified_by, modified_on,
modified_from FROM user WHERE OLD.user_id = user_id;
SQL query: Documentation
delimiter // CREATE TRIGGER log_user_delete BEFORE DELETE ON user FOR EACH ROW BEGIN INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
MySQL said: Documentation
#1064 - 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 'delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW' at line 1.
what am I doing wrong?
2 tables :-
CREATE TABLE user (
user_id INT(11) NOT NULL AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
modified_from VARCHAR(20) NOT NULL,
PRIMARY KEY (user_id)
);
CREATE TABLE log_user (
log_id INT(11) NOT NULL AUTO_INCREMENT,
user_id INT(11) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on DATETIME,
modified_from VARCHAR(20) NOT NULL,
log_modified_by INT(11) NOT NULL,
log_modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
log_modified_from VARCHAR(20) NOT NULL,
status VARCHAR(10) NOT NULL,
PRIMARY KEY (log_id)
);
Trigger :
DELIMITER //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
UPDATE log_user SET status = 'DELETED' WHERE log_id = last_insert_id();
END;
// DELIMITER ;
My Code:
create table Products
(
ProductID int not null auto_increment primary key,
ProductName varchar(20),
Recommendedprice decimal(10,2),
Category varchar(10)
)
create table customers
(
CustomerID int not null auto_increment primary key,
FirstName varchar(50),
LastName varchar(50),
city varchar(50),
State char(2),
zip varchar(10)
)
create table sales
(
SalesID int not null auto_increment primary key,
ProductID int,
CustomerID int,
CONSTRAINT fk_PerProducts FOREIGN KEY (ProductId)
REFERENCES Products(ProductId),
CONSTRAINT fk_PerCustomers FOREIGN KEY (CustomerId)
REFERENCES customers(customerId),
SalesPrice decimal(10,2),
SalesDate date
)
I get null values in the table list.
You need to send the id of the foreigner key when you make an INSERT.
like this (paper_Author work like your sales table) :
CREATE TABLE Paper (`paperId` int, `title` varchar(7));
INSERT INTO Paper (`paperId`, `title`)
VALUES (1, 'hello'),(2, 'hola'),(3, 'bonjour');
CREATE TABLE Author (`authorId` int, `authorName` varchar(3));
INSERT INTO Author (`authorId`, `authorName`)
VALUES (1, 'me'),(2, 'moi');
CREATE TABLE Paper_Author (`paperId` int, `authorId` int);
INSERT INTO Paper_Author (`paperId`, `authorId`)
VALUES (1, 1),(1, 2),(2, 2);
and you use it like this :
http://sqlfiddle.com/#!2/eb61f/2
other think you should read :
Basics of Foreign Keys in MySQL?
Why use Foreign Key constraints in MySQL?
I have populated all my databases with the information needed before i created the final table with my foreign key constraints referencing them but when i view the final table with a select * from mytbl my foreign key values are coming back as null values. i have been going through this site and my textbook for an hour trying to figure out what i have wrong but i am not seeing it. here is my code that i have used for the database.
Create Database Donutsrus;
Create table customer
(CustomerID int not null auto_increment,
FirstName varchar(255) not null,
LastName varchar(255) not null,
StreetAddress char(255) not null,
Apartment varchar(255) not null,
City varchar(255) not null,
State varchar(2) not null,
ZipCode int(9) not null,
HomePhone int(10) not null,
MobilePhone int(10) not null,
OtherPhone int(10) not null,
Primary Key (CustomerID));
insert into Customer
(FirstName, LastName, StreetAddress, Apartment, City, State,
ZipCode, HomePhone, MobilePhone, OtherPhone)
Values ("Ken", "Weger", "StreetAddress", "Apartment", "City",
"ST", 123456789, 1111111111, 222222222, 333333333);
Create Table Donut
(Quantity int(255) not null,
DonutID int(255) not null auto_increment,
Name varchar(255) not null,
Description varchar(255) not null,
UnitPrice decimal(3,2) not null,
LineTotal Decimal(10,2) not null,
Primary Key (DonutID));
insert into Donut (Quantity, Name, Description, UnitPrice, LineTotal)
Values ("1", "Plain", "Plain Donut", "1.50", "1.50"),
("5", "Glazed", "Glazed Donut", "1.75", "8.75"),
("12", "Cinnamon", "Cinnamon Donut", "1.75", "21.00"),
("3", "Chocolate", "Chocolate Donut", "1.75", "5.25"),
("4", "Sprinkle", "Sprinkle Donut", "1.75", "7.00"),
("5", "Gluten-Free", "Gluten-Free Donut", "2.00", "10.00");
Create Table DonutOrder
(DonutOrderID int(255) not null auto_increment,
CustomerID int(255),
DonutID int(255),
`Date` date not null,
SpecialHandlingNotes Varchar(255),
Primary Key (DonutOrderID),
Index Customer (customerid),
Foreign Key (CustomerID) References Customer(CustomerID),
Index Donut (donutid),
Foreign Key (DonutID) References Donut(DonutID));
Insert into DonutOrder (`Date`, SpecialHandlingNotes)
Values ("20140506", "Please Include Plates and Napkins");
If I add a not null syntax after customerid and donutid in the donutorder database i get this
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`donutsrus`.`donutorder`, CONSTRAINT `donutorder_ibfk_1` FOREIGN KEY (`CustomerID`) REFERENCES `customer` (`CustomerID`)).
You should insert values for the foreign key fields. For instance:
Insert into DonutOrder (
`Date`,
SpecialHandlingNotes,
CustomerId,
DonutId
)
values ( "20140506",
"Please Include Plates and Napkins",
(select CustomerId from Customer where MobilePhone = 222222222),
(select DonutId from Donut where Name = 'Plain')
);
I'm working in MySQL 5.5.
I've got a Contacts table like this
CREATE TABLE Contacts
(
ID INTEGER NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
Institution VARCHAR(255),
Address VARCHAR(255),
Email VARCHAR(255) NOT NULL UNIQUE,
Phone VARCHAR(10)
);
and an Inventories tables like this
CREATE TABLE Inventories
(
ID INTEGER NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
InventoryParametersID INTEGER NOT NULL UNIQUE,
ContactID INTEGER NOT NULL,
LocationID INTEGER NOT NULL,
Year INTEGER,
DateUploaded TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
Comments VARCHAR(255),
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
);
In my webform, contacts upload inventories. Here's the behavior I want:
- When a new contact uploads an inventory, do an insert with their new info
- When an existing contact (determined by email address) uploads another inventory, update their info AND retain referential integrity with the Inventories table
How do I do this?
Here's what I've tried:
CASE
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
REPLACE INTO Contacts (`Name`, `Institution`, `Address`, `Email`, `Phone`) VALUES (?, ?, ?, ?, ?);
RESULT
No change
CASE
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
ON UPDATE CASCADE
REPLACE INTO Contacts (`Name`, `Institution`, `Address`, `Email`, `Phone`) VALUES (?, ?, ?, ?, ?);
RESULT
No change
A REPLACE deletes find row and add a new. So your ON UPDATE CASCADE doesn't work. Why do you not use an INSERT ... ON DUPLICATE KEY UPDATE?
INSERT INTO Contacts (Name, Institution, Address, Email, Phone)
VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE
Name = VALUES(NAME),
Institution = VALUES(Institution) ...
MySQL DOC
I am trying to avoid inserting duplicates records into my table by using the PRIMARY KEY and INSERT IGNORE methods. As suggested # http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
I added the PRIMARY KEY to the tables definition as shown below:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id, flightNo, status)
)")
or die(mysql_error());
echo "Table Created!";
Find below the INSERT IGNORE code:
mysql_query("INSERT IGNORE INTO Alteration
(depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name)
VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' ) ");
// or die(mysql_error());
echo "Number of affected rows were: " . mysql_affected_rows();
While testing it I noticed that it STILL inserts duplicate records.
Why is it still doing this? Can anyone help me point out what is wrong?
Any help is greatly appreciated.
Looking forward to your feedback.
Your id column is auto incrementing which means each row is effectively unique when it is used in your key. You should inspect the data that you've inserted. You should see that each duplicate row actually has a separate and distinct id.
You can set a UNIQUE index on flightNo and status which would prevent the duplicate rows.
ALTER TABLE `Alteration` ADD UNIQUE (
`flightNo` ,
`status`
);
And then I would recommend just reducing your Primary Key to be id
UPDATE
As requested, this is a modified version of your code with a unique index used to prevent the duplicates:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id),
UNIQUE KEY `flightNo` (`flightNo`,`status`)
)") or die(mysql_error());
echo "Table Created!";
mysql_query("INSERT IGNORE INTO Alteration (depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name) VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' )");
echo "Number of affected rows were: " . mysql_affected_rows();