HOW TO CREATE A MYSQL RELATIONAL DATABASE

In this tutorial, will we show you how to create a MySQL database for a Content Management System (CMS) that we will be creating in an upcoming tutorial. Once you create a database, you have three things to do with tables:

  1. Create them
  2. Relate them
  3. Populate them

Before we can create a MySQL database, it is best practice to download a bundle software package to install the necessary resources that are needed to create it. There are a host of packages available (i.e., LAMP, MAMP, ZendAMF, etc.). However, we will download a popular package known as XAMPP.  XAMPP will install Apache, MySQL, Perl and PHP. The "X" in XAMPP represents one of four operating systems (Windows, Mac, Solaris, Linux) that are supported.

Installing XAMPP (If neccessary)

If you do not already have XAMPP installed, follow the procedures below:

  1. Download XAMPP to your computer. (Go to http://www.apachefriends.org/en/xampp.html)
  2. Double click on the installation file to install XAMPP.  While installing XAMPP, if you accept the default options, it will be installed in the c:/xampp directory unless you specified otherwise.
    NOTE: If you don't have permission you can install XAMPP in whatever folder you want. However, for the sake of this tutorial, we will install it in hte default location mentioned earlier.
  3. Open the XAMPP Control Panel Application dialog box (All Programs > ApacheFriends > XAMPP Control Panel) and turn on Apache and MySQL by clicking on the Start button for both.
    NOTE: You can stop either services by clicking on their Stop button.



    NOTE: You should see the word Apache and MySql highlighted in green to let you know that both services started correctly. In  older versions you should see the word Running higlighted next to Apache and MySql.

  4. Test to see if the server is set up correctly to "serve up" pages by typing http://localhost or http://127.0.0.1 into a web browser (i.e., Firefox or Internet Explorer).

    NOTE: For Mac users the path is: http://localhost/~username/phpMyAdmin/

  5. Click on a language (i.e., English) on the page that is displayed.

    NOTE: You should see anohter page with a title of "XAMPP for Windows" and a note that says "Congratulations: You have successfully installed XAMPP on this system!"

It is important to remember that you type a URL (http://localhost) that points to a FILE DIRECTORY (C://xampp/htdocs/MyApplicationFolder/).
When you test the server, you should see a page that displays XAMPP directory.  If you get a message that states page cannot be displayed, check:

Normalizing Data (Information only)

Duplicated data can cause errors every time records in a database is inserted, updated or deleted and can lead to unpredictable results such as the inability of entering data into a database. Duplicate data happens when two or more fields are inadvertently combined into a single table. To avoid this from happening, if the table is designed using a process called normalization, it will be free from duplicates. To normalize tables, you have to split the tables into separated tables with the correct fields in them. A database is said to be normalized when each fields contain one value and each table has the correct number of fields. Normalization can be summarized as follow:

Creating a MySQL Database

Typically, the first step in creating a dynamic database application is to create a database. 

IMPORTANT NOTE: While the steps are generic; however, the values (in bold and blue) are specific to the upcoming lesson.

  1. Type in localhost (or 127.0.0.1) in a browser and then click on the phpMyAdmin button in the left sidebar.
    TIP: A shortcut to phpMyAdmin is localhost/phpmyadmin/.
  2. Give the database a name (in our case, type rmcs_corporation1234) in the Create new database field and then click the Create button.
    TIP: It is important to give your database a name the can not be easily hacked. This is the reason the 1234 was added to the database name.
    NOTE: MySQL will automatically convert any database name to all lowercase so you may want to insert underscores between words (i.e., tb_student_directory).

Creating Tables for the Database

After you create the database, you need to create table(s) inside of it.  In our case, we will be creating the following four tables for our CMS that we will be using in an upcoming lesson:

It is best practice to create a Entities Relationship Diagram  (ERD) to define tables structure before creating a MySQL database. It can be difficult to change some aspect of a table once it is created and you may have to recreate it if it is not done correctly.  Also, before populating a table, you need to define its structure which includes.

Click on the tab below to see detail information on how to structure a table:

Table Stucture Information (Click to open tab and click again to close tab)
  • Determining the number of columns – This should be determine from the ERD.
  • Naming the tables/columns – (1-64 characters – $, numbers, letters and underscore) with a descriptive name. It is best practice to give the table a prefix  (i.e., tb_student_directory). Table can begin with a number but can not be exclusively all numbers.
    NOTE: You can not use MySQL reserve words (i.e., date, time, etc.) when you create column names. Instead use a compound word like pick_up_date or drop_off_date.
  • Setting column data type – Below is a list of the most common data types that may need further explanation:
    • Storing text:
      • CHAR – fixed length width text up to 255 characters. You can define a default value.
        NOTE: If you insert data that is larger than the allocated space, the data will be truncated in the database.
      • VARCHAR – variable length width text up to over 65K. You can define a default value.
      • TEXT – stores a maximium of 65K of text.  Use can not define a default value. It is useful because you do not have to specify a maximum size.
        TIP: Use VARCHAR for short text and TEXT for long text.
    • Storing numbers:
      • TINYINT – whole numbers (integer) between -2,147,483,648 and 2,147,483,648.  If the column is declard as UNSIGNED, the range is 0 to 4,294,967,295. Notice that we you used unsigned the range double on the positive values.
      • INT – whole numbers (integer) between -128 and 127. If the coumn is declard as UNSIGNED, the range is 0 to 255
      • FLOAT – Any floating-point number.
      • DECIMAL – Any floating-point number that is stored as a string.
        NOTE: Decimal is used mainly for currency. However, since it is stored as a string, it is best avoided if you plan to do any kind of calculation with currency. It is best to use INT and then use PHP to divide the result by 100 and then format the currency. 
        NOTE: Do not use commas or spaces in your currency. You can only use the negative sign ( - ) or the period ( . ).
    • Storing dates and times:
      • DATE – store date as YYYY-MM-DD
        NOTE: MySQL by defaults stores dates as YYYY-MM-DD
      • DATETIME – date and time is displayed (i.e., YYYY-MM-DD HH:MM:SS)
      • TIMESTAMP – will generate a computer system timestamp.
    • Storing pre-defined lists:
      • ENUM – store a single choice from a predefined list (i.e., yes, no or male, female).
      • SET – store zero or more choices up to 64 from a predefined list.  It is useful when an item form a complete unit (i.e., optional extras)
        NOTE: ENUM and SET are stored in a comma separate string. Individual values can include spaces but not commas for obvious reason.
    • Storing binary data (BLOB - Binary Large Objects):
      • TINYBLOB – store up to 255 bytes
      • BLOB – store up to 64KB
      • MEDIUMBLOB – store up to 16MB
      • LONGBLOB – store up to 4GB
  • Determining the Default Values – self explanatory.
  • Determing the Collation (Sort Order) – Collation determines the sort order of records for entire database, individual table or column.  Unless you are using another language other than English, Swedish, or Finnish, you should leave the Collation drop-down box at its default.
  • Deternining the Attributes – You can set whether the value is binary, unsigned, unsigned, unsigned zerofill or on update CURRENT_TIMESTAMP
  • Setting whether column fields are required to have data – By placing a check in the Null column, you are saying that the field can be null. If you want the null field to be REQUIRED, uncheck the null checkbox. It is common practice to not have the field values to allow nulls. This way, you can create client side code to validate data that will be entered into the database.  If you set a default value for a NOT NULL, MySQL will automatically use that default value if nothing is entered for that field.
  • Setting table's index – (primary, unique, index and fulltext) Every table should have a primary key even if  you don't intend to use it currently.
  • Determining if the field will auto increment –  When setting the primary key, it is a common practice to set this field as auto increment.
  • Adding comments – self explanatory.
  • Setting the MIME type
  • Setting the Browse transformation and transformation options –

Click on the tab below to see detail information that is common to all tables that you will create.

Notes common to all tables (Click to open tab and click again to close tab)

NOTES COMMON TO ALL TABLES:

  • It is important to note the some columns are dependent on other columns. For example, If you set the Data Type column to VARCHAR, you must specify a length or value in the Length/Value column and an optional default value in the Default column:
  • When creating a database driven application, it is common practice  that none of the fields be required (except the primary key fields).  It is better to perform form validation to ensure that the data the user will enter meets your requirements. If you allow the database to determine if a field is required, when the missing data is encountered a sometime useless error is thrown. If you use form validation, you can customize the error with instruction on how to resolve it. By default, all of the columns are set to NOT NULL (or Required). To make the columns OPTIONAL, you have to select all of the checkboxes (of course, except when the A_I option is selected for a field which is typically used in conjunction with the table's primary key).
  • All primary key fields will have Auto Increment (A.I.)
  • Additional fields (columns) can be added later, if necessary.
  • Is it best practice to estimate how many characters is needed for a given field because the field sizes determines the size of the database. However, if the data field is too small, MySQL will truncate the data is it is too large for the field.
  • Every table has a primary key with its field name set to the name of the table and a suffix of "ID" (i.e., EmployeeID).  Also, its data type checked for Auto Increment.
  • If you click on the Home button (the first icon) in the left sidebar at the top, you will see a list databases listed below it.
  • If you go back to edit a table, you will not see the INDEX column. It is shown at  the bottom of the table once it is created.

 

Create First Table:

  1. In the table page, type a table name (in our case, type Students) in the Create new table text field.
  2. Type the number of fields you need for your database (in our case, type 13) in the Number of Fields text field box and click the Go button to save the table.
  3. Type or select the information you need for the first row. In our case, type:
    1. Type field name (i.e., StudentID) in the Field column
    2. Select data type (i.e., INT) in the Type column
    3. Type number of column (i.e., 11) in the Length/Value column or you can not type anything and it will default to 11
    4. Select index type (i.e., PRIMARY) for the Index column
    5. Select checkbox of AI (Auto Increment) column
    6. Leave other columns at their default.
  4. Click the Save button to save the current table.
  5. Repeat steps 1-3 for the other rows. In our case, in rows 2-13, click the first tab below to see the additional fields we added for each row.
    NOTE: phpMyAdmin will create a link in the sidebar to the table you just created.

Create Other Tables:

  1. Click on the database name in the left sidebar. This will allow you to create a new table.



  2. Repeat steps 1-5 for any additional tables you need to create.  In our case, use the information in the tables below by clicking on a tab below for each table info. Table cells that are left blank below implies that default values will be used or it is not appliable to the value for those fields. For example, you don't need to set a Length/Value for Date or Time because the Data Type determines the lenght/value for it.

Student Directory

The Student Directory table will store student information. Give the table a name of tb_StudentDirectory.

Studnet Direcory Table
Field Name Type Length/Value Null Index Auto Increment
StudentID INT     Primary check
LastName VARCHAR 50 check    
FirstName VARCHAR 50 check    
Address VARCHAR 50 check    
City VARCHAR 25 check    
State VARCHAR 2 check    
ZipCode VARCHAR 10 check    
HomePhone VARCHAR 12 check    
Title VARCHAR 50 check    
Department VARCHAR 50 check    
Extension INT 10 check    
HireDate DATETIME   check    
EditPages BOOLEAN   check    

NOTE: The EditPages will be used in the CMS to determine who has access to edit pages. It will be used with the Department field to determine who can edit pages but what department can be edited.

Information Services

The Information Services table will store assets (i.e., computer, phone,etc.) assigned to employees. Give the table a name of tbInformationServices.

Information Services Table
Field Name Type Length/Value Null Index Auto Increment
AssetID INT     Primary check
StudentID VARCHAR 11 check    
AssetType VARCHAR 25 check    
AssetBrand VARCHAR 25 check    
AssetModel VARCHAR 50 check    
AssetSerial VARCHAR 50 check    
DateAssigned DATE   check    
DateReturned DATE   check    
ReturnReason LONGTEXT   check    

Department Site Management

The Department Site Management table will allow each department to update data contained in its intranet site by clicking on each tab. Give the table a name of tbDeptSiteManagement.

Department Site Management Table
Field Name Type Length/Value Null Index Auto Increment
PageID INT     Primary check
Department VARCHAR 50 check    
PageTitle VARCHAR 100 check    
NavLink1Text VARCHAR 50 check    
NavLink1URL VARCHAR 50 check    
NavLink2Text VARCHAR 50 check    
NavLink2URL VARCHAR 50 check    
NavLink3Text VARCHAR 50 check    
NavLink3URL VARCHAR 50 check    
MainPageData LONGTEXT   check    
LastUpdated DATE   check    

Username/Password

The Username/Password table will store student username and passwords as the phrase implies to allow the users to log in and log out. Give the table a name of tbUsernamePassword.

Username/Password Table
Field Name Type Length/Value Default Null Index Auto Increment
UserNamePasswordID INT       Primary check
StudentID VARCHAR 11   check    
Username VARCHAR 50   check Unique  
Password VARCHAR 40   check    
FirstName VARCHAR 30   check    
LastName VARCHAR 30   check    
Admin_Privilege ENUM 'n','y' n check    
LastLogin DATE     check    

NOTE: Notice there is an additional column (Default) that has been added for the Admin_Privilege field.

  • The UserNamePasswoedID field Lenght/Value is not needed because the Auto Increment is selected and it will determine the lenght of the field
  • Since you do not want anyone to have the SAME username, the UNIQUE option is set for the index type for the Username field so that the same value cannot be entered twice. This can be done with a server behavior as well.
  • The Password field Length/Value is set to 40 because a function will be used later to encrypt the password  to a hexadecimal string of 40 characters.
  • The Admin_Privilage field Type value is set to ENUM with the Lenght/Value set the ('n', 'y') and the defaulf value set to "n". All three of the values works together. The values in the Lenght/Value field has to be separated with commas and each value has to be in quotes.


NOTE: Usernames and passwords are stored in a separate table so that student data is not VISIBLE to the students.

 

 

Relating Tables (Need Updating to MySQL instead of MS Access)

After a database has been created and tables inserted into it. It is important to create "relationship" between particular tables. Because EACH asset must be assigned to a user from the tbHumanResources table, a relationship between these two tables will be created. Also, because a username and password is assigned to EACH employee from the tbHumanResources table, a relationship between these two table will be created as well.

  1. With the database (in our case, rmcs_database1234.mdb) still open, select Tools > Relationships from the menu.
  2. In the Show Table dialog box that appears, select all four tables and click the Add button.
    NOTE: Tables must be saved to see all fields listed.
  3. Click on the Close button to close the Show Table dialog box.
    NOTE: You should see the four tables in the Relationships window.
  4. Click the EmployeeID field in the tbInformationServices and drag it onto the EmployeeID field in the tbHumanResources box.
    NOTE: A one-to-many relationship is created  which means that one employee record in the tbHumanResources table can have many records in the tbInformationServices table (i.e., phone, computer, etc.).
  5. In the Edit Relationships dialog box, check ALL three options and then click the Create button.
    NOTE: By checking the Referential Integrity, when a record is delete from the tbHumanResources database, the records will also be deleted in the tbInformationServices database.
  6. Click and drag the EmployeeID field in the tbUsernamePassword box onto the EmployeeID field in the tbHumanResources box.
  7. Again, select all three check boxes and click the Create button to create a relationship between these two tables.
  8. Close the Relationships window and save the file.
    NOTE: If you are prompted with a Security Alert, click on the Option button and select the "Enable this content."

Populating Tables

After you create a database and its table(s), you will need to populate those tables. You can either populate the tables from within:

We will be populating these tables in upcoming tutorials from within the web application that will be create.

Setting Privilege and Creating A User

When you installed MySQL, it created one registered user called "root" which allow unfeathered access to all of the databases. This should only be used by the administrator with a username and password that is created. It is best practice to create a user access for each specific database as well. Typically, the administrator has complete access and users have limited access.

Create administrative access by creating a password:

  1. Click on the Privileges tab at the top of the page to view a list of user accounts.
    NOTE: If this is a new installation, you should only see the root user account.
  2. Click on the Edit Privileges icon under the Action column and the row root of the table to open the Edit Privileges screen.
  3. In the Global Privileges, click on the Check All link at the top of the screen to select all of the checkboxes for Data, Structure, and Administration sections.
    NOTE: Notice that four Data privileges types matches the SQL command types (i.e., SELECT, INSERT, UPDATE and DELETE).
  4. In the Change Password section, select the Password radio button and then type the same password in botth field.
  5. Leave Password Hasting at its default.
  6. Click the Go button in the Change password section.
    NOTE: If you selected "config" as the authentication type when you set up phpAdmin, you need to update the config.inc.php file manually by updating the following line: $cfg['Servers'] [$i] ['passord'] = 'enterNewPassWordHere' ;

You can create user accounts that can have fewer privilleges, if necessary, for a single database.

Create user privileges:

  1. Click on the Privileges tab at the top of the page to view a list of user accounts.
    NOTE: If this is a new installation, you should only see the root user account.
  2. Click on the Add a new User link at the bottom of the page.
  3. In the Login Information section, change the following settings:
    1. Type a user name in the second field of the User name row.
    2. Click on the drop-down menu next the the word Host to select localhost to show the word localhost in the second field.
    3. Type the same password in teh Password and Re-type fields.
  4. In the Global privileges section, simply click the Go button.
    NOTE: You should see a confirmation that says "You have added a new user."
    NOTE: You don't want to grant access to all of the database.
  5. In the Database-specific privileges, select the option you need and then click the Go button.
    NOTE: To delete a user, click on the localhost link and the select the user you want to delete by clicking on the checkbox next to it and then click the checkbox in the Remove selected users section and then click the Go button.