A foreign key constraint fails - php

I am relatively new in php and mysql.The problem that i am facing while i inserting value in my leave table.My leave table containing following column..
1.lid(INT primary key)
2.empname(varchar)
3.username(varchar)
4.nod(INT)
5.sdate(DATE)
6.edate(DATE)
7.reason(varchar)
8.action(varchar)
9.empID (INT FOREIGN KEY)
here empID is the foreign key references from users table. The problem that im facing while inserting values into the leave table.ERROR is given below
Cannot add or update a child row: a foreign key constraint fails (db_attendance1.leave, CONSTRAINT leave_ibfk_1 FOREIGN KEY (empID) REFERENCES users (empID))
here i just send the query and here it is..
mysql_query("INSERT INTO `leave`
(`empname`, `username`,
`nod`, `sdate`, `edate`,
`reason`,`action`)
VALUES ('$empname', '$username',
'$nod', '$sdate',
'$edate', '$reason','');",
$dbCon) or die(mysql_error());

You can put
SET FOREIGN_KEY_CHECKS=0;
and run your query. Once you are done again set it back to 1 by
SET FOREIGN_KEY_CHECKS=1;

A foreign key constraint means that you one table doesn't accept inserts, updates or deletes that would 'break' the foreign key. This means, you can't update a EmpID if the new EmpID doesn't exist in the users. You can't add a new EmpID if it doesn't exist in the users table, etcetera.
So to solve this issue, you need to make sure that the EmpID you're trying to add to table 'leave', first exists in table 'users'.
Foreign keys can be a real powerful item, but can be a real pain too. Since the DB you're working on had foreign key constraints, I suggest you read on them a bit: http://en.wikipedia.org/wiki/Foreign_key

Borniet, you helped me solve my similar problem.
#OP - All I had to do to fix this was create a corresponding row in the table so that the foreign key would exist.
E.g. Table 1 has column Name
Table 2 has column friends_name, a foreign key tied to Name in table 1.
I got this error because I was trying to insert a row into table 2, where the friends_name referenced a non existing Name in table 1. So I created the name and we're off to the races :).

Related

Mysql duplicate row prevention [duplicate]

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

implementing referntial integrity with php mysqli

i have three tabs in my Db:
1.pers_info(id(primary), name ,....)
2.contacts(c_id(primary), phone, email, ...)
now 1 person can have multiple rows in contacts tab.
thus to minimize redundancy i made another tab contact_relation(id (foregin key references pers_info(id), c_id (foregin key references contacts(c_id))
i successfully created the relation and also was able to insert apt entries(related id and c_id) to it "using last_insert_id();" to extract id and c_id required.
now the problem..
i dropped tab contacts_rel. and created it this way :
CREATE TABLE contacts_relation (
id INT NOT NULL,
cid INT NOT NULL,
FOREIGN KEY (id)
REFERENCES pers_info(id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (c_id)
REFERENCES contacts(c_id)
);
if now i try to insert into tab cont_rel, it gives error :
cannot add or update a child row foreign key constraint fails.
which makes sense..
i was hoping that adding constraints in the defn of tab cont_rel would save the hassle of inserting entries in it manually using "last_insert_id();"
so is there a way, i could maintain ref integrity with new data
coming.. thanks.
Why the third table? When you many to many relation you need intermediate table. You have one to many relation so two tables are sufficient. Table contacts need FK to table pers_info. Add it if you don't have already.
Here's a simple transaction example with LAST_INSERT_ID(): SQL INSERT INTO multiple tables
Some info about foreign keys and altering table:
Add Foreign Key to existing table
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html

foreign key prevents deletion of data in mysql

I'm designing a website of book library for my project in php.
Anyways I have three tables named books,users and savebook.
Table book has following columns: "bookid", "title","author" "genre" and "summary".
And table users has following columns userid, username, password, and name.
Users can save books as favorites and those saved books are saved in the table named savebook with columns bookid and userid which are foreign key to table book and users
I used following query for that:
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid);
and
ALTER TABLE savebook
ADD CONSTRAINT usid_bkid
FOREIGN KEY (userid)
REFERENCES users(userid);
Now the problem is whenever i try to delete a book from table book using query
DELETE FROM books
WHERE bookid=1;
I get this message:
1451 - Cannot delete or update a parent row: a foreign key constraint fails (booklibrary.savebook, CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid))
How do i delete a book from table book which also deletes the related row in table savebook?
To get the behavior you describe, you can specify
ON DELETE CASCADE
as part of the foreign key definition.
Reference: http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
If you were to modify your foreign key constraint bkid_usid (on the booksave table), then the delete statement that you show
DELETE FROM books WHERE ...
Would cause MySQL to delete the rows in booksave that have a foreign key values that reference rows being removed from books.
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid)
ON DELETE CASCADE
;
Make note of that last line I added to the ALTER from the original question, it is an optional part of the foreign key definition (there is also ON UPDATE ...). By default, when not specified, I believe MySQL treats it as NO ACTION or RESTRICT (those two are effectively the same as far as I know) instead of CASCADE. Full documentation found at http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
An interesting question :)
I think the problem is caused by the so called "referential integrity".
That means, that you are not able to delete a dataset, which primary key is used in another tables dataset as foreign key. If you could do this, some foreign keys of the table savebook would refer to a dataset in table books, that doesn't exist anymore.
So first you have to delete all datasets in savebook, where the bookid is the same one as of the book you want to delete and after that, you can delete this dataset from books. ;)
You have applied constraints to the tables. You need to tell MySQL to delete referenced entries from "savebook" table if any entry is deleted from "book" table.
ALTER TABLE savebook ADD CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid) ON DELETE CASCADE

Cannot add or update a child row: a foreign key constraint fails. what is this?

sorry, i am still new in php... i want to ask... how actually foreign key is functional? i mean, i have create a foreign key and primary key, everything fine. i try look in internet, but still i cant make it work or did mistake that i dont know. i get this error "Cannot add or update a child row: a foreign key constraint fails" when i try to insert information inside my other table that have foreign key
my parent table "user_information" have:
user_id = primary key
user_password
name
user_category
group_id
and my other "table vehicle_registration" have:
plate_number = primary key
user_id = foreign key
roadtax_validation
vehicle_category
user_option
insurance name
i want to make the user that log in can insert their vehicle registration, and it bind to that user, the user_id should be similar, just other information is diferent... how i can make it? is it correct that the foreign key is to work like that? cause when i try to insert value inside the vehicle_registration it will show "Cannot add or update a child row: a foreign key constraint fails"
can someone explain how it actually done?
You have to add user/s first. You can't add a record in vehicle_registration table if you dont have a matching record in the parent table.
That is how foreign key constraint works. For example if you have a record in user_information table with user_id = 1, you are only allowed to have records with user_id = 1 in the vehicle_registration table. And so on...

Cannot add or update a child row: a foreign key constraint fails

Can anyone help me with this database error, I'm inserting data on a table named
subjectdetails(
subjectid int primarykey,
subject varchar(50),
semid int //foreign key from the table semester
departmentid int(11) // foreign key from the table department
)
Now, when i insert a subject it only shows the error on SEMID like the below error
Cannot add or update a child row: a foreign key constraint fails
(`studentcorner/subjectdetails`, CONSTRAINT `subjectdetails_ibfk_1` FOREIGN KEY
(`SEMID`) REFERENCES `semester` (`SEMID`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Please help me with this..
The error is indicating that you have a foreign key constraint which cannot be satisfied. Specifically, you're trying to insert a subjectdetails entry with an invalid semid column. The value you're using for semid is invalid because that value cannot be found inside the semester table. I know this because your error message states as much.
To fix this error, ensure that the value you're trying to insert for the semid column actually exists in the semesters table first.
I would suggest going to the documentation and re-read the section on Using Foreign Key Constraints. The relevant quote from that page regarding your issue is this (emphasis mine):
For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

Categories