How to create a foreign key in phpmyadmin - php

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

Related

Can I create a composite key for a third table from the primary keys of 2 different tables? Does MySQL support it?

I have got 3 different tables:
review table-> this has mov_id as the primary key.
users_table -> this has username as the primary key.
review_table -> can I make a composite primary key for this table from movie_id and username?
users table
reviews table
comments table
I can't connect these 3 tables and I can't figure out why.
This is the error I'm getting while creating the comments table
You can create composite primary key with foreign keys (primary keys from others tables), you have nothing special to do. Just constrain the foreign keys and declare them as primary.
With the names of tables and columns you provided, here's a query to create the table you want :
CREATE TABLE review_table (
movie_id INT,
username VARCHAR(255),
-- Change INT and VARCHAR(255) by what you used on the others tables
PRIMARY KEY (movie_id, username),
FOREIGN KEY (movie_id) REFERENCES movies_table(movie_id),
FOREIGN KEY (username) REFERENCES users_table(username)
)

SQL::PDO remove path to image from db if recipe is removed [duplicate]

I am trying to figure out relationships and deletion options.
I have two tables, User and UserStaff, with a 1:n relationship from User to UserStaff (a user can have multiple staff members).
When my User is deleted, I want to delete all of the UserStaff tables associated with that User. When my UserStaff is deleted, I don't want anything to happen to User. I understand that this is a cascading relationship, but I'm not sure which way.
i.e. Do I select the existing foreign key in my UserStaff table and make it cascading, or do I create a new foreign key in User and set that to cascading?
Yes, it's possible. You should make the FK in UserStaff table. In this way:
User Table
CREATE TABLE `User` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UserStaff Table
CREATE TABLE `UserStaff` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`UserId` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
KEY `UserId` (`UserId`),
CONSTRAINT `UserStaff_ibfk_1`
FOREIGN KEY (`UserId`)
REFERENCES `User` (`Id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
From Wikipedia:
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
Here, User is the master table, and UserStaff is the child table. So, yes, you'll want to create the foreign key in UserStaff, with ON DELETE CASCADE
It's been a while since I've used this, but here goes (btw, I use Toad for MySql - a great IDE, and it's free too - http://www.toadworld.com/Freeware/ToadforMySQLFreeware/tabid/561/Default.aspx!)
You need to add a Constraint to the User table. If you have an id column (and the corresponding foreign userid key in UserStaff) then the SouceColumn should be id, the destination table UserStaff and the destination column userid. You can then set the OnDelete action to be 'Cascade'
The other options are pretty self-explanatory - Restrict limits values to the values in the source column, Set Null sets the foreign key matches to Null and No Action does, er, nothing.
This stuff is very easy to do via the Toad IDE. I used MySqlAdmin tools for ages but recently discovered Toad (and it has diff and compare tools too!).
The ON DELETE CASCADE is specified on the foreign key in the UserStaff table. For additional info on foreign keys the MySQL documentation has a number of examples. The User table does not have a foreign key pointing to UserStaff, so it will not be affected by changes to the UserStaff table.
The easiest way might be to make two quick tables and try it out. But since you didn't I can tell you that the outcome will be that it work the way that you want to.
When you have a table User and a table UserStaff were a field in UserStaff uses a foreign key to reference a field in User; then if you delete a record from UserStaff that will be removed wihtout having any affect on the User table. The other way around will delete all records related to that record.
Short version: A field in UserStaff should reference a field in User with CASCADE

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

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.

phpmyadmin doesnt allow me to add primary/foreign key relationship

That is the primary table field (tasks table):
task_id int(10) UNSIGNED No None AUTO_INCREMENT
This is my foreign table field (url_error_stats table):
task_id int(10) UNSIGNED No None
url_error_stats doesnt present the "relation view" option to connect between the keys..why?
SQL query:
ALTER TABLE url_error_stats ADD FOREIGN KEY ( task_id )
REFERENCES aws_backlinks.tasks (
task_id ) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL said:
1452 - Cannot add or update a child row: a foreign key constraint
fails (aws_backlinks., CONSTRAINT #sql-6f0_3bd_ibfk_1 FOREIGN KEY
(task_id) REFERENCES tasks (task_id) ON DELETE CASCADE ON UPDATE
CASCADE)
you have to use innodb and index the primary key if you want to create the foreign keys. and I will recommend you to use NAVICAT . its much easier to create foreign keys and quick too. but for a quick phpmyadmin guide see
Setting up foreign keys in phpMyAdmin?
Another reason can be the unrelated data in your tables. I mean you may have a foreign key that doesn't exist in parent table.
in this , click on url_error_stats table, then on right hand side it will show all the fields list, so now check on checkbox of that particular field which u wanted to be foreign and click on the link relation view (which is provided by phpmyadmin below to the table fields with blue color hyperlink).
it will open relationship screen , there You can select the field of the primary table.
Thanks

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()

Categories