Saturday, 13 October 2007

Project a database: create tables and relationships with SQL

In the previous lesson we have seen how to design the relationship-entities model for a database to be used in a del.icio.us-like web site project. Our R-E model is:



Now we implement the database using SQL and phpMyAdmin. We crate a new database on phpMyAdmin and select the "SQL" tab. Copy and paste this SQL code into the form and click on execute button:

CREATE TABLE USER (
id_user_pk INT NOT NULL AUTO_INCREMENT,
nick VARCHAR(40),
email VARCHAR(40),
password VARCHAR(20),
user_reg_date DATE,
PRIMARY KEY (id_user_pk)
) TYPE=INNODB;

CREATE TABLE SITE (
id_site_pk INT NOT NULL AUTO_INCREMENT,
site_url VARCHAR(250),
site_description LONGTEXT,
site_data_reg DATA,
PRIMARY KEY
) TYPE=INNODB;

CREATE TABLE SHARE (
id_share_pk INT NOT NULL AUTO_INCREMENT,
id_user INT NOT NULL,
id_site INT NOT NULL,
submitted_by INT NOT NULL DEFAULT 0,
PRIMARY KEY (id_share_pk),
FOREIGN KEY (id_user) REFERENCES USER(id_user_pk) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (id_site) REFERENCES SITE(id_site_pk) ON UPDATE CASCADE ON DELETE CASCADE
) TYPE=INNODB;


Create Relationships
To create relationships between database's table (for example between SHARE table and the other tables) you have to use the SQL code below:

FOREIGN KEY (attribute_name_1) REFERENCES tableOfReference(attribute_name_2)


where attribute_name_1 is the foreign key (generally, a field of type INTEGER)a and attribute_name_2 the primary key of the table of destination.

To force the referencial integrity between the data of database, you have to add this code:

ON UPDATE CASCADE ON DELETE CASCADE


Our database is now ready and we can implement it using PHP and MySQL

No comments:

Post a Comment