MYSQL- Create and store primary key in master and child table - php

I got stuck while insertion into database tables.
I have below tables.
I dont have any fields which can be make as Primary key.
Here "eme_request" and "eme_attachment" is master tables.
I want to know that how can I insert into tables ?
These tables(eme_request, eme_gf_relevent, eme_non_gf_relevent, eme_attachment) are getting insertion on one form request.
So I am not getting how to generate primary key in master table and how to insert into child table with that primary key as a Foreign key ?

In eme_request table REQ_ID (your PK) is type of varchar. If you can change it to INT and add flag AUTOINCREMENT, you will get automatically generated key.
If you can't change type of REQ_ID (you need it to be char), just add abstract PRIMARY_KEY int column and use it.
After inserting into table with autoincrement column you can receive assigned key with
https://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id so it can be used as FOREIGN KEY for other tables.

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.

How to create a foreign key in phpmyadmin

I want to make doctorid a foreign key in my patient table.
So I have all of my tables created - the main problem is that when I go to the table > structure > relation view only the primary key comes up that I can create a foreign key (and it is already the primary key of the certain table that I want to keep - i.e Patient table patient is enabled to be changed but the doctor Id -I have a doctor table also- is not enabled).
I have another table with two composite keys (medicineid and patientid) in relation view it enables me to change both
Do I have to chance the index of doctor ID in patient table to something else? both cannot be primary keys as patient ID is the primary for the patient table - doctor is the foreign.
I hope anyone can help
Kind regards
You can do it the old fashioned way... with an SQL statement that looks something like this
ALTER TABLE table_1_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (table_1_column_name)
REFERENCES target_table(target_table_column_name);
For example:
If you have books table with column created_by which refers to column id in users table:
ALTER TABLE books
ADD CONSTRAINT books_FK_1
FOREIGN KEY (created_by)
REFERENCES users(id);
This assumes the keys already exist in the relevant table
The key must be indexed to apply foreign key constraint. To do that follow the steps.
Open table structure. (2nd tab)
See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
Open relation view and add foreign key constraint.
You will be able to assign DOCTOR_ID as foreign now.
To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab.
Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.
Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.
See attachments. I hope this could be useful for anyone.
Create a categories table:
CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
Create a products table and reference categories table:
CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
Create a vendors table and modify products table:
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key (referencing vendors table) to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
If you wish to drop that key then:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
In phpmyadmin, Go to Structure tab, select Relation view as shown in image below.
Here you will find the tabular form to add foreign key constrain name, current table column, foreign key database, table and column

A foreign key constraint fails

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 :).

How to set a foreign key and retrieve or delete data from multiple tables?

I am new to php and mysql. I created a database named 'students' which contain two tables as 'student_details' which have fields like 'ID, Name, Age, Tel#, Address' and another table as 'fee_details' which have fields like 'ID(student_details table ID), Inst Id, Date, Receipt No'.
I want to set a foreign key and retrieve data from both tables when a student paid their fees and if a student passed out or discontinued I want a delete option to delete his all records from my tables. So please help me to solve this by PHP code and displays it in HTML while using a search form.
Enforcing referential integrity at the database level is the way to go. I believe when you said you wanted the delete "to delete his all records from my tables" you meant deleting the row and all its child records. You can do that by using foreign keys and ON DELETE CASCADE.
CREATE TABLE students
(
student_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
) ENGINE=INNODB;
CREATE TABLE fee_details
(
id INT,
date TIMESTAMP,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
ON DELETE CASCADE
) ENGINE=INNODB;
With this, when a student is deleted from the students table, all its associated records will be deleted from fee_details.
you can try mysql_query() and mysql_assoc_array()

autoincrement as primary key causing duplicate entries

I want an id and name to be primary key for my table. I want to increment id with every insert, so i set it to auto_increment. The problem is when i insert into table a new entry with same name, it inserts it with a new id and there are duplicate entries with same name and different ids. I don't want to search the table beforehand to see if there is any entry beforehand. Please help me how to correct this problem.
I think you have done something like this
CREATE TABLE table1
id unsigned integer autoincrement,
name varchar,
....
primary key (id,name)
This primary key does not select on unique name, because the autoincrement id will always make the key as a whole unique, even with duplicate name-fields.
Also note that long primary keys are a bad idea, the longer your PK, the slower inserts and selects will execute. This is esspecially bad on InnoDB, because the PK is included in each and every secondary key, ballooning your index files.
Change it to this
CREATE TABLE table1
id unsigned integer autoincrement primary key,
name varchar,
....
unique index `name`(name)
If you want it to be unique by name, you need to add a unique index on the name field, and then you can use the mysql syntax for on duplicate key: mysql reference for on duplicate key
You could apply a unique index to your name field, or if you're storing people, allow duplicate names.
Add UNIQUE(your_column_name) where you should replace your_column_name with the column in your database.

Categories