59
Fundamentals of Web Development Randy Connolly and Ricardo Hoar © 2017 Pearson http://www.funwebdev.com Working with Databases Chapter 14

Working with Databases

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Fundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar© 2017 Pearson

http://www.funwebdev.com

Working with Databases

Chapter 14

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development The Role of Databases in Web Development

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development How websites use databases

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development Database Design

A database in a Relational DBMS is composed of one or more tables.

A table is a two-dimensional container for data that consists of records (rows);

Each record has the same number of columns, which are called fields, which contain the actual data.

Each table will have one special field called a primary key that is used to uniquely identify each record in a table.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development

Normally taught in an entire course. This is a refresher.

Database Design

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development Diagramming a table

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development Integrity

A database can enforce rules about what can be stored.

This provides data integrity and potentially can reduce the amount of data duplication.

This is partly achieved through the use of data types that are akin to those in a programming language.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Data typesCommon Database Field Types

Type Description

BIT Represents a single bit for Boolean values. Also called BOOLEAN or BOOL.

BLOB Represents a binary large object (which could, for example, be used to store an image).

CHAR(n) A fixed number of characters (n = the number of characters) that are padded with spaces to fill the field.

DATE Represents a date. There is also a TIME and DATETIME data types.

FLOAT Represents a decimal number. There are also DOUBLE and DECIMAL data types.

INT Represents a whole number. There is also a SMALLINT data type.

VARCHAR(n) A variable number of characters (n = the maximum number of characters) with no space padding.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Relationships between TablesDifferent cardinalities

Tables that are linked via foreign keys are said to be in a relationship:

• One-to-many relationshipsingle record in Table A can have one or more matching records in Table B

• Many-to-many relationshipMany-to-many relationships are implemented by using an intermediate table with two one-to-many relationships

• One-to-one relationshipTypically used for security or performance reasons. (Could be 1 table)

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

One-to-Many

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Many to ManyUse an intermediate table

Note that in this example, the two foreign keys in the intermediate table are combined to create a composite key

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Databases and Web Development Foreign keys

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLThere are many other open source and proprietary relational DBMS, including:

• PostgreSQL

• Oracle Database

• IBM DB2

• Microsoft SQL Server

• MySQL

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQL

There is a Data Definition Language (DDL) in SQL, which is used for creating tables, modifying the structure of a table, deleting tables, and creating and deleting databases

There is also the Data Manipulation Language (DML) in SQL, which uses the SELECT , UPDATE , INSERT , and DELETE statements.

Two sides

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Create Table ConstructExample:

create table instructor (ID char(5),name varchar(20),dept_name varchar(20),salary decimal(8,2),primary key(ID)

)

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Integrity Constraints in Create Table not null primary key (A1, ..., An ) foreign key (Am, ..., An ) references (r)

Example:

create table instructor (ID char(5),name varchar(20) not null,dept_name varchar(20),salary numeric(8,2),primary key (ID),foreign key (dept_name) references (department));

Note: the primary key declaration on an attribute automatically ensures not null

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Insertion Add a new row to course

insert into coursevalues (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

or equivalentlyinsert into course (course_id, title, dept_name, credits)

values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

Add a new row to student with tot_creds set to nullinsert into student

values (’3003’, ’Green’, ’Finance’, null);

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Updates to tables Delete

– Remove all tuples from the student relation• delete from student

Drop Table– drop table r

Alter – alter table r add A D

• where A is the name of the attribute to be added to relation r and D is the domain of A.

• All exiting tuples in the relation are assigned null as the value for the new attribute.

– alter table r drop A • where A is the name of an attribute of relation r• Dropping of attributes not supported by many

databases.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Other useful commands Select the name of the database to use:

use dbname;

Tables in the current databaseshow tables;

Table structure (information about a table’s attributes)

describe tablename;

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLSELECT Statement

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLSELECT Statement

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLUse the WHERE clause

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLJoin together

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLMember group by

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLINSERT, UPDATE, and DELETE Statements

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLINSERT, UPDATE, and DELETE Statements

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQLINSERT, UPDATE, and DELETE Statements

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

SQL

By starting the transaction, all database modifications within the transaction will only be permanently saved in the database if they all work

START TRANSACTIONINSERT INTO orders . . .INSERT INTO orderDetails . . .UPDATE inventory . . ./* if we have made it here everything has worked so commit changes */

COMMIT/* if we replace COMMIT with ROLLBACK then the three database changes would be "undone" */

Transactions

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Database APIs

• MySQL extension. This was the original extension to PHP for working with MySQL and has been replaced with the newer mysqli extension.

• mysqli extension. This extension provides both a procedural and an object-oriented approach. This extension also supports most of the latest features of MySQL.

• PHP data objects (PDOs). provides an abstraction layer that with the appropriate drivers can be used with any database, and not just MySQL databases. However, it is not able to make use of all the latest features of MySQL.

PHP MySQL APIs

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Database APIs

While PDO is unable to take advantage of some features of MySQL, there is a lot of merit to the fact that PDO can create database-independent PHP code

• Like many things in the web world, there is no single best choice.

• As the chapter (and book) proceed, we will standardize on the object-oriented, database-independent PDO approach.

Deciding on a Database API

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Managing a MySQL Database phpMyAdmin

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

1. Connect to the database.

2. Handle connection errors.

3. Execute the SQL query.

4. Process the results.

5. Free resources and close connection.

Basic Connection Algorithm

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP Basic Connection Algorithm

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

// modify these variables for your installation$host = "localhost";$database = "bookcrm";$user = "testuser";$pass = "mypassword";$connection = mysqli_connect($host, $user, $pass, $database);

Connecting to a Database (mysqli procedural)

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

// modify these variables for your installation$connectionString = "mysql:host=localhost;dbname=bookcrm";$user = "testuser";$pass = "mypassword";$pdo = new PDO($connectionString, $user, $pass);

Connecting to a Database (PDO Object-oriented)

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);

// mysqli_connect_errno returns the last error code

if ( mysqli_connect_errno() ) {

die( mysqli_connect_error() ); // die() is equivalent to exit()

}

Handling Connection Errors - mysqli

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

try {

$connString = "mysql:host=localhost;dbname=bookcrm";

$user = DBUSER;

$pass = DBPASS;

$pdo = new PDO($connString,$user,$pass);

. . .

}

catch (PDOException $e) {

die( $e->getMessage() );

}

Handling Connection Errors - PDO

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$sql = "SELECT * FROM Categories ORDER BY CategoryName";

// returns a mysqli_result object

$result = mysqli_query($connection, $sql);

OR

$result = $pdo->query($sql);

Executing the Query

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

//closes the connection

mysqli_close($connection);

Freeing Resources and Closing Connection

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$sql = "UPDATE Categories SET CategoryName='Web' WHERE

CategoryName='Business'";

$count = $pdo->exec($sql);

echo "<p>Updated " . $count . " rows</p>";

Working with Parameters

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Sanitizing Query Strings

Just because you are expecting a proper query string, doesn’t mean that you are going to get a properly constructed query string.

• distrust all user input

The process of checking user input for incorrect or missing information is sometimes referred to as the process of sanitizing user inputs.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Form validation

Why?• Error management• Security Objectives1. Make sure something was entered or selected2. Ensure that submitted data is of

a. The right type b. The right formatc. An acceptable value

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Form validation

HTML5 will help with form validation:– Input types: email, date, tel, url, etc. See:

http://www.w3schools.com/html/html5_form_input_types.asp

– The required attribute. See: http://www.w3schools.com/html/html5_form_attributes.asp

Useful functions:• empty($var)• isset($var)• is_numeric ($var)

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Form validation

Name Description Best use

empty($var) Returns TRUE if the variable has been set and is not NULL

Text input

isset($var) Returns TRUE if the variable hasn't been set, contains a NULL value, or contains an empty string.

Non-text input: radio buttons, check boxes, submit. etc.

is_numeric ($var) Returns TRUE if the variable is a number or a string that can be converted to a number

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Form validation Useful functions for converting user-entered

data for output/display:

Name Description

trim($string) Returns a new string with white space trimmed from both sides of the string.

htmlspecialchars($string) Converts certain HTML special characters (&, ', ", < and >) to their corresponding HTML entities. For example & becomes &amp;

htmlentities($string) Converts all HTML characters that have corresponding HTML entities and returns the resulting string.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Validating data by type

is_array() is_bool() is_float() is_int() is_null()

is_numeric() is_resource() is_scalar() is_string()

Each data type that PHP supports has a corresponding function that checks if a variable is of that type.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

The filter_input function

The arguments:Name Description

type Specifies the superglobal variable to access. Common values include INPUT_GET, INPUT_POST, INPUT_COOKIE

variable_name The name of the value to retrieve

filter Optional. The constant for the filter to apply.

Name Description

filter_input($type, $variable_name [, $filter)

Gets a value from a superglobal variable and optionally filters it. Returns the requested value on success, a FALSE value if the filter fails, or a NULL value if the requested value is not set.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Common constants for filters

Name Description

FILTER_VALIDATE_INT Validates an integer value.

FILTER_VALIDATE_FLOAT Validates a floating-point (double) value.

FILTER_VALIDATE_EMAIL Validates an email address.

FILTER_VALIDATE_URL Validates a URL.

FILTER_VALIDATE_BOOLEAN Returns a TRUE value for "1", "true", "on", or "yes". Otherwise returns a FALSE value.

FILTER_SANITIZE_STRING Returns the string after removing tags and removing or encoding special characters from a string.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Validation filters examples

$product_description = filter_input(INPUT_GET, 'product_description');//Null if product_description has not been set in the $_GET array

$investment = filter_input(INPUT_POST, 'investment', FILTER_VALIDATE_FLOAT);//Null if investment has not been set in the $_post array//FALSE if 'investment' is not a valid float (double) value

Considered best practice to always use the filter_input functions when you use values from a superglobal array.

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$sql = "INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,ProductionStatusId, TrimSize, Description) VALUES (?,?,?,?,?,?,?)";$statement = $pdo->prepare($sql);$statement->bindValue(1, $_POST['isbn']);$statement->bindValue(2, $_POST['title']);$statement->bindValue(3, $_POST['year']);$statement->bindValue(4, $_POST['imprint']);$statement->bindValue(5, $_POST['status']);$statement->bindValue(6, $_POST['size']);$statement->bindValue(7, $_POST['desc']);$statement->execute();

Working with Parameters – Technique 1 ? Placeholders

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

/* can pass an array, to be used in order */

$sql = "INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,ProductionStatusId, TrimSize, Description) VALUES (?,?,?,?,?,?,?)";$statement = $pdo->prepare($sql);$statement->execute array(array($_POST['isbn'], $_POST['title'],$_POST['year'], $_POST['imprint'], $_POST['status'], $_POST['size'],$_POST['desc']));

Working with Parameters – Technique 1 ? Placeholders with Array

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$sql = "INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,ProductionStatusId, TrimSize, Description) VALUES (:isbn,:title, :year, :imprint, :status, :size, :desc) ";$statement = $pdo->prepare($sql);$statement->bindValue(':isbn', $_POST['isbn']);$statement->bindValue(':title', $_POST['title']);$statement->bindValue(':year', $_POST['year']);$statement->bindValue(':imprint', $_POST['imprint']);$statement->bindValue(':status', $_POST['status']);$statement->bindValue(':size', $_POST['size']);$statement->bindValue(':desc', $_POST['desc']);$statement->execute();

Working with Parameters – Technique 2 - named parameters

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$sql = "INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,ProductionStatusId, TrimSize, Description) VALUES (:isbn,:title, :year, :imprint, :status, :size, :desc) ";$statement = $pdo->prepare($sql);$statement->execute(array(':isbn' => $_POST['isbn'],

':title'=> $_POST['title'],':year'=> $_POST['year'],':imprint'=> $_POST['imprint'],':status'=> $_POST['status'],':size'=> $_POST['size']':desc'=> $_POST['desc']));

Working with Parameters – Technique 2 - named parameters with Array

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP Getting user input into a query

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Accessing MySQL in PHP

$pdo = new PDO($connString,$user,$pass);

try {// begin a transaction$pdo->beginTransaction();// a set of queries: if one fails, an exception will be thrown$pdo->query("INSERT INTO Categories (CategoryName) VALUES ('Philosophy')");$pdo->query("INSERT INTO Categories (CategoryName) VALUES ('Art')");// if we arrive here, it means that no exception was thrown$pdo->commit();

} catch (Exception $e) {// we must rollback the transaction since an error occurred with insert$pdo->rollback();

}

Using Transactions

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Case Study Schemas Book CRM Database

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Sample Database TechniquesSearch and Results Page

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Sample Database TechniquesEditing a Record

Fundamentals of Web Development - 2nd Ed.Randy Connolly and Ricardo Hoar

Sample Database TechniquesEditing a Record