简体   繁体   中英

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.

您可以尝试mysql_query()mysql_assoc_array()

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM