Part 2
Concepts Design Basics Command-line MySQL Security Loophole
Databases Flat-file Database stores information in a single table usually adequate for simple collections of information Relational Database suited for large and complex collections of information stores information across multiple related tables
Basic Types of Table Relationships 1. one-to-one 2. one-to-many 3. many-to-many
Basic Types of Table Relationships 1. one-to-one relationship exists between two tables when a related table contains exactly one record for each record in the primary table (instead of having one BIG table) Suitable when you want to break information into multiple, logical sets Why? You might want to make certain information confidential; thus, separate as another table to limit its access e.g. Employees, Payroll
Basic Types of Table Relationships 2. one-to-many relationship exists in a relational database when one record in a primary table has many related records in a related table suitable for eliminating redundant information in a single table. Ideally, only primary and foreign keys are the only pieces of information that should be duplicated. Breaking tables into multiple related tables to reduce redundant information is called normalisation.
Basic Types of Table Relationships 2. one-to-many relationship Breaking tables into multiple related tables to reduce redundant information is called normalisation. Normalisation reduces the size of the database and decreases the opportunity for error when the same information is repeated. Let s have a look at an example...
STRUCTURE Table: Customers CONTENTS
STRUCTURE Table: Products CONTENTS
STRUCTURE Table: Purchases CONTENTS
Relationship between Tables Create relationships within the database by working with two tables at a time One table in a relationship is always considered to be the primary table, and the other table is considered the related table. Primary Table (or Parent Table) the main table in a relationship that is referenced by another table. Related Table (of Child Table) references a primary table in a relational database
Example: Customers - Primary Table Primary key Foreign key Purchases - Related Table
Basic Types of Table Relationships 3. many-to-many relationship Exists in a relational database when many records in one table are related to many records in another table You must use a junction table to create a manyto-many relationship Junction table (or linking/cross-reference table) Creates a one-to-many relationship for each of the tables in a many-to-many relationship Let s have a look at an example...
Basic Types of Table Relationships 3. many-to-many relationship Junction table (or linking/cross-reference table) Creates a one-to-many relationship for each of the tables in a many-to-many relationship Employee_id firstname lastname Employee_id language 101 dug Dog 102 kevin Bird 101 English 101 Tagalog 101 Spanish One-to-many relationship Not normalised because the language field contains duplicate values We could use many-to-many relationship here instead 102 Spanish 102 English
Basic Types of Table Relationships 3. many-to-many relationship Junction table (or linking/cross-reference table) Employee_id firstname lastname Language_id language 101 dug Dog 102 kevin Bird Employee_id Language_id Proficiency level 101 English 7 101 Tagalog 10 101 Spanish 4 102 Spanish 5 102 English 8 10 English 11 Tagalog 12 Spanish 13 French 14 Finnish 15 Korean One-to-many relationship
Relational Database Example Read a customer record, and then show the products purchased by that customer. Tables Remember the database example we used in the previous lecture? Customers Products Purchases PurchaseProducts Example15-14.php
STRUCTURE Table: PurchaseProducts (data) CONTENTS
Database Design Cost at the time of purchase
Logging in to MySQL mysql -h host -u user -p
Show available databases An SQL command ends with a semicolon;
SQL Commands When you enter an SQL command at the mysql> command prompt you must terminate the command with a semicolon. the SQL keywords you enter in a MySQL monitor are not casesensitive. However, the case-sensitivity of database and table identifiers depends on your operating system. Convention: although you can use any case for SQL keywords, follow the convention of using uppercase letters for SQL keywords and using lowercase or mixed case for the names of databases, tables, and fields.
Creating a database Creates a folder for the database To use the newly created database Returns the currently active database
Show available databases
Creating a table CREATE TABLE table_name (column_name TYPE,...); Creates a table named vehicles Display table structure
Altering a table ALTER TABLE table_name ADD [COLUMN] (column_name TYPE,...); Add a new field to the table Display table structure To delete a Table: DROP TABLE table_name;
Creating user accounts GRANT privilege[,privilege] ON database_name.* TO username@"%" IDENTIFIED BY "somepassword"; Create an account named dug Logging-in ALL - all privileges database_name.* - any table in the database username@"%" username @ any host "somepassword user password
Common MySQL privileges Privilege ALL ALTER CREATE DELETE DROP INDEX INSERT SELECT UPDATE USAGE Description Assign All privileges to the user Allow to modify the table structure All to create databases, tables, and indices Allow to delete records Allow to delete databases and tables Allow to create and delete indexes Allow to add records Allow to select records Allow to modify records Create user with no privileges
Deleting a database DROP DATABASE database_name; Delete the vehicle_fleet database
Commands help;? Command descriptions exit quit log-out of MySQL monitor
http://xkcd.com/327/
SQL Injection It makes perfect sense to make use of a proper database to manage a growing user population and user authentication. However, we need to be aware of a loop hole that makes our application vulnerable to security breach. Let s have a look at an example...
Database name: users Consider the following database example: Database Name: users, containing only one Table named users. Table users is defined with only 3 fields, as shown below: STRUCTURE Primary key
Database name: users for this example we have only one table named users CONTENTS Users and their passwords
SQL Injection-prone script! <?php $strusername = " ' OR '0 "; $strpassword = ''; An attacker could use the following combination $dblocalhost = mysql_connect("localhost", "root", "") or die("could not connect: ". mysql_error()); mysql_select_db("users", $dblocalhost) or die("could not find database: ". mysql_error()); $dbrecords = mysql_query("select * FROM users WHERE username= '$strusername' "); $intcount = mysql_num_rows($dbrecords ); echo "<p>count: ". $intcount. "</p>"; $arrrecords = mysql_fetch_array($dbrecords); echo $arrrecords["password"]; if ($strpassword!= $arrrecords["password"]) echo "<p>invalid Password/UserName</p>"; else echo "<p>password and UserName match!</p>";?> sqlinjection_prone2.php
SQL Injection-prone script! <?php $strusername = " ' OR '0 "; $strpassword = ' ';... mysql_query("select * FROM users WHERE username= '$strusername' "); After substitution of values, the statement becomes: mysql_query("select * FROM users WHERE username= ' ' OR '0 ' "); This statement will force the query not to return any records, and as the password is set to NULL, the if statements comparing the passwords evaluates to true. Therefore, the script thinks that the username and password matches. sqlinjection_prone2.php
<?php $strusername = "' OR '0"; $strpassword = ''; SQL Injection-safe script! $dblocalhost = mysql_connect("localhost", "root", " ) or die("could not connect: ". mysql_error()); mysql_select_db("users", $dblocalhost) or die("could not find database: ". mysql_error()); $strusername = mysql_real_escape_string($strusername); $dbrecords = mysql_query("select * FROM users WHERE username='$strusername'"); $arrrecords = mysql_fetch_array($dbrecords); if (mysql_num_rows($dbrecords)!= 1) echo "<p>username not found!</p>"; else { if ($strpassword!= $arrrecords["password"]) echo "<p>invalid Password/UserName</p>"; else echo "<p>password and UserName match!</p>"; }?> sqlinjection_secure.php
SQL Injection-safe script! <?php $strusername = " ' OR '0 "; $strpassword = ' ';... $strusername = mysql_real_escape_string($strusername); mysql_query("select * FROM users WHERE username= '$strusername' "); After substitution of values, the statement becomes: mysql_query("select * FROM users WHERE username= ' \' OR \'0 ' "); The mysql_real_escape_string function escapes quotation characters in the SQL string removing the danger of the quotes being Interpreted incorrectly by the SQL parser. In addition, it is important to count the number of records returned using mysql_num_rows() as another security measure. sqlinjection_secure.php
Database name: users Consider creating a database named users, containing only one Table named users. Table users is defined with only 3 fields, as shown below: STRUCTURE Apply MD5() function