class 8 - database programming

43
Database Programming

Upload: ahmed-swilam

Post on 15-Apr-2017

439 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Class 8 - Database Programming

Database Programming

Page 2: Class 8 - Database Programming

Outline

• MySQL• How it works• Data Types• Data Definition Language• Data Manipulation Language• MySQL Comments• Where clause• Comparison Operators• ORDER Clause• LIMIT Clause• Escaping Characters• MySQL Joins• Using MySQL in PHP

• Methods to use• Connecting to a database• Querying a database• Exercise• Exercise Solution• Prepared Statements• Tips and Tricks• Resources• Course Project• Assignment

Page 3: Class 8 - Database Programming

MySQLMySQL is a Relational Database Management System (RDBMS) which stores data in a structured way ( in tables ).It allows for retrieving data using Structured Query Language (SQL).

MySQL Server

Web Server ( Apache with PHP )

Web BrowserRequest

Que

ry

Resu

lt se

t

Response

Page 4: Class 8 - Database Programming

How it worksHow tables look like ?

id name salary job_title

1 Ahmed 100 Developer

2 Mohamed 200 Doctor

3 Sara 300 Engineer

4 Marwa 400 Designer

Page 5: Class 8 - Database Programming

How it works• In MySQL, we can have multiple databases, every

database has an unlimited amount of tables.• A table holds data about some entity ( person, employee,

etc ).• The table consists of number of columns, each column

can have a data type ( char, int, float, etc… )

Page 6: Class 8 - Database Programming

Data TypesSize Name Range Example1 TINYINT -128 TO 127

[0 to 255 if UNSIGNED] 10

2 SMALLINT -32,768 to 32,767[0 to 65,535] 30000

3 MEDIUMINT -8,388,608 to 8,388,607[0 to 16,777,215] 8000000

4 INT -/+2.147E+9[0 to 4.294E+9] 80000000

8 BIGINT -/+9.223E+18[0 to 18.45E+18] 80000000000

4 FLOAT p=0-24 4.333333

8 DOUBLE Min=+/-2.225E-308Max=+/-1.798E+308

.000000000000000000003

arbitrary DECIMAL[(M,[D])]Stored as string Max Range = DOUBLE range 33333.4444

M CHAR(M) M=0-255 Characters, FIXED.Right padded with spaces. Hello There

M VARCHAR(M) M=0-65,535 CharactersM=0-255 <v5.0.3 Hello There

Page 7: Class 8 - Database Programming

Data TypesSize Name Range Examplearbitrary TINYTEXT 0-255 Characters Hello Therearbitrary TEXT 0-65,535 Char's Hello Therearbitrary MEDIUMTEXT 0-16,777,215 Char's Hello Therearbitrary LONGTEXT 0-4,294,967,295 Char's Hello Therearbitrary BINARY[(M)] M=0-255 bytes, FIXED.

arbitrary VARBINARY(M) 0-65,535 bytesM=0-255 <v5.0.3

arbitrary TINYBLOB 0-255 bytesarbitrary BLOB 0-65,535 bytesarbitrary MEDIUMBLOB 0-16,777,215 bytesarbitrary LONGBLOB 0-4,294,967,295 bytes

3 DATE "1000-01-01" - "9999-12-31" 2010-01-01

8 DATETIME "1000-01-01 00:00:00" -"9999-12-31 23:59:59" 2010-01-01 10:12:01

3 TIME "-838:59:59" - "838:59:59" 10:12:01

4 TIMESTAMP 19700101000000 -2037+ 19700101000000

Page 8: Class 8 - Database Programming

Data Definition LanguageDDL in the language MySQL use to define its data structures ( databases and tables ).

Example :

CREATE TABLE employees ( id INT PRIMARY KEY, first_name CHAR(50) NULL, last_name CHAR(75) NOT NULL, salary INT NOT NULL DEFAULT 0, dateofbirth DATE NULL);

Page 9: Class 8 - Database Programming

Data Definition LanguageAltering tables:Adding or removing columns or changing the data types of columns.

Examples:

ALTER TABLE employees ADD salary INT(11);

ALTER TABLE employees MODIFY salary FLOAT(10,5);

ALTER TABLE employees DROP salary;

Page 10: Class 8 - Database Programming

Data Definition LanguageRemoving a table:

DROP table employees

Removing a database:

DROP DATABASE db_name;

Page 11: Class 8 - Database Programming

Data Manipulation LanguageDML is the language used by MySQL to manipulate data ( select, insert, update, delete )

SELECT statement:It is used to get data from a table.

Example :SELECT * FROM employees

The previous statement should select all the data from the employees table.

SELECT first_name FROM employeesThis should return the column “first_name”

Page 12: Class 8 - Database Programming

Data Manipulation LanguageINSERT statementsThey are used to insert a new row into a table.

Examples:

INSERT INTO employees SET id=1, first_name='John', last_name='Steve', dateofbirth = '1970-01-01‘

INSERT INTO employees (id, first_name, last_name, dateofbirth ) values ( '2', ‘John', 'Steve', '1970-01-01' )

Page 13: Class 8 - Database Programming

Data Manipulation LanguageUPDATE statementsThese statements are used to update (change) data.

Example:

UPDATE employees SET first_name = ‘Mohamed’

This will update all the rows in the employees table setting the “first_name” to “Mohamed”

Page 14: Class 8 - Database Programming

Data Manipulation LanguageDELETE statementsThese statements are used delete rows from a table.

Example:

DELETE FROM employees;

This will delete all rows from employees table.

Page 15: Class 8 - Database Programming

MySQL CommentsJust like any other programming language, MySQL has ways to comment code.

1. -- one line comment2. # one line comment3. /*

MultiLineComment*/

Page 16: Class 8 - Database Programming

Where clauseWhere clauses are used to restrict the operations to a limited number of rows (the rows the satisfy this condition).

Examples:

SELECT * FROM employees WHERE first_name = ‘Mohamed’

DELETE FROM employees WHERE first_name = ‘John’

Update employees SET first_name = ‘Mohamed’ WHERE last_name = ‘Ahmed’

Page 17: Class 8 - Database Programming

Comparison OperatorsOperator Description

= Equals

!= Not Equals

<> Not Equals

>= Greater than or equal

<= Less than or equal

IS NULL True if the field is not null, false otherwise

IS NOT NULL True if the field is null, false otherwise

BETWEEN … AND … Checks if the value is between the specified numbers

NOT BETWEEN … AND … Checks if the value is not between the specified numbers

IN ( …, …, …, ) Checks if the value is in the specified list

NOT IN Checks if the value is not in the specified list

LIKE Checks if the value is like the specified string.

NOT LIKE Checks if the value is not like the specified string. See next slide

Page 18: Class 8 - Database Programming

Comparison Operators ExamplesSELECT * FROM employees WHERE salary <= 20

SELECT * FROM employees WHERE salary BETWEEN 10 AND 20

SELECT first_name FROM employees WHERE last_name LIKE ‘%ham%’ # percentage ‘%’ matches zero or more characters

SELECT * FROM employees WHERE first_name NOT LIKE ‘__ham__’ # underscore matches 1 character

SELECT * FROM employees WHERE salary IN ( 10, 20, 30 )

Page 19: Class 8 - Database Programming

ORDER ClauseORDER clauses are used to order the result set.

Examples:

SELECT * FROM employees ORDER BY first_name ASC# ASC = ascendingly

SELECT * FROM employees ORDER BY last_name DESC# DESC = descendingly

Page 20: Class 8 - Database Programming

LIMIT ClauseLimit clauses are used to limit the number of rows in a result set.

Examples:

SELECT * FROM employees LIMIT 1# gets only the first row

SELECT * FROM employees LIMIT 1 , 2# gets 2 rows starting from the first row ( it gets the second and third rows )

Page 21: Class 8 - Database Programming

Escaping CharactersMySQL is similar to PHP when escaping characters :

SELECT * FROM employees WHERE first_name = ‘That\’s me’

SELECT * FROM employees WHERE first_name = “That\”s me”

But it adds another method of escaping :

SELECT * FROM employees WHERE first_name = ‘That’’s me’

SELECT * FROM employees WHERE first_name = “That””s me”

Page 22: Class 8 - Database Programming

MySQL JoinsMySQL joins allow us to get data from multiple tables in the same query. Suppose we have the following tables:

id name salary job_title1 Ahmed 100 Developer2 Mohamed 200 Doctor3 Sara 300 Engineer4 Marwa 400 Designer

id model CC employee_id

1 BMW 1600 1

2 Hyundai 1600 2

3 Honda 1800 3

4 Fiat 1600 4

Employees table

Cars Table

Page 23: Class 8 - Database Programming

MySQL JoinsThe previous tables are employees and cars tables. Every car has an owner which is an employee.If we need to get data from these 2 tables, we will need to join them like the following :

SELECT employees.name, cars.model FROM employees, cars WHERE employee.id = cars.id

name modelAhmed BMW

Mohamed HyundaiSara Honda

Marwa Fiat

Result set

Page 24: Class 8 - Database Programming

Using MySQL in PHPTo achieve dynamism, a connection between a language and database is essential. PHP has a great MySQL support. There are various methods/ approaches that we could use to connect to MySQL in PHP.

Page 25: Class 8 - Database Programming

Methods to useWe have 3 methods of code styles that we can use to connect to MySQL in PHP.

1- Procedural approach.2- MySQLi approach.3- PDO ( PHP Data Objects ) approach.

We Will user PDO because it is OOP and it supports named parameters and exceptions plus it has a good abstraction model that supports many drivers.

Page 26: Class 8 - Database Programming

Connecting to database<?php

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';$user = 'dbuser';$password = 'dbpass';

try { $connection = new PDO($dsn, $user, $password);} catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage();}

?>

Page 27: Class 8 - Database Programming

Querying a databaseHere we will need to display the last name of the people with first_name = ‘Mohamed’.

<?php$sql = "SELECT * FROM employees WHERE first_name =

'Mohamed'";

$result = $connection->query($sql); foreach ($result as $row) { print $row['last_name'] . "<br/>"; }?>

Page 28: Class 8 - Database Programming

Querying a databaseInserting a new row into employees table :

<?php$sql = “INSERT INTO employees SET first_name = ‘Ahmed’,

last_name = ‘Gamal’, salary = 300";

$connection->query($sql);

?>

Page 29: Class 8 - Database Programming

Querying a databaseGetting the number of rows in the result set:

<?php$sql = "SELECT * FROM employees WHERE first_name =

'Mohamed'";

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

echo “Number of rows : “ . $result->rowCount();?>

Page 30: Class 8 - Database Programming

ExerciseWrite a PHP application the inserts a new employee into the ‘employees’ table. There should be a form that looks like the following wireframe :

Page 31: Class 8 - Database Programming

Exercise SolutionWe will have a script named “form.php” with the following HTML:<html>

<body><form action="add.php" method="post" >

<ul style="list-style-type: none;"><li><label for="first_name">First name</label>

<input type="text" name="first_name" id="first_name" /></li><li><label for="last_name">Last name</label>

<input type="text" name="last_name" id="last_name" /></li><li><label for="salary">Salary</label>

<input type="text" name="salary" id="salary" /></li><li><label for="dateofbirth">Date of birth</label>

<input type="text" name="dateofbirth" id="dateofbirth" /></li><li><input type="submit" name="submit" value="submit" /></li>

</ul></form>

</body></html>

Page 32: Class 8 - Database Programming

Exercise SolutionThe other script is called “add.php” which contains :<?php$dsn = 'mysql:dbname=testdb;host=127.0.0.1';$user = 'dbuser';$password = 'dbpass';

try { $connection = new PDO($dsn, $user, $password); $sql = "INSERT INTO employees SET first_name = '" . $connection->quote($_POST['first_name']) . "', last_name = '" . $connection->quote($_POST['last_name']) . "', salary = " . $connection->quote($_POST['salary']) . ", dateofbirth = '" . $connection->quote($_POST['dateofbirth']) . "'"; $connection->query($sql); echo "Record has been added.";} catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage();}?>

Page 33: Class 8 - Database Programming

Escaping values passed to MySQLIt is advised that any values sent to MySQL should be escaped using the function called “quote” (like the previous example). In addition to preventing syntax errors in SQL statements, it is a top security concern ( google “SQL injection”, for more information about this type of security issue).

PDO::quote($str);

Page 34: Class 8 - Database Programming

Prepared statementsPrepared statements are the ability to set up a statement once, and then execute it many times with different parameters.

Example :

SELECT * FROM employees WHERE first_name = ?

SELECT * FROM employees WHERE first_name = :first_name

Page 35: Class 8 - Database Programming

Prepared statementsOne of the key advantages of prepared statements is the ability to bind parameters.

Binding parameters can be done using one of the approaches:1- The question marks “?”.2- Named parameters ( e.g. “:first_name”, “:last_name”, etc).

Page 36: Class 8 - Database Programming

Prepared statements1- Question marks:

<?php $connection = new PDO($dsn, $user, $password); $sql = "INSERT INTO employees SET first_name = ? , last_name = ?, salary = ?,

dateofbirth = ?";

$sth = $connection->prepare($sql);

$sth->bindParam(1, $_POST['first_name']); $sth->bindParam(2, $_POST['last_name']); $sth->bindParam(3, $_POST['salary']); $sth->bindParam(4, $_POST['dateofbirth']);

$sth->execute()

?>

Page 37: Class 8 - Database Programming

Prepared statements2-Named parameters:

<?php $sql = "INSERT INTO employees SET first_name = :first_name , last_name

= :last_name, salary = :salary, dateofbirth = :dateofbirth";

$sth = $connection->prepare($sql);

$sth->bindParam(':first_name', $_POST['first_name']); $sth->bindParam(':last_name', $_POST['last_name']); $sth->bindParam(':salary', $_POST['salary']); $sth->bindParam(':dateofbirth', $_POST['dateofbirth']);

$sth->execute();?>

Page 38: Class 8 - Database Programming

Prepared statementsWhy to use prepared statements:

1- Security; as the developer is not responsible for escaping parameters passed to MySQL.

2- MySQL parses each query before executing it, so if we are going to execute the same query with different data values, prepared statements are the optimized solution since the query will be compiled ( prepared ) only one time, and then the data will be substituted in the query each time we execute it.

Page 39: Class 8 - Database Programming

Resourceshttp://dev.mysql.com/doc/http://php.net/manual/en/book.mysql.phphttp://www.php.net/manual/en/intro.pdo.php

Page 40: Class 8 - Database Programming

Course ProjectDetailed explanation of the project. The project document will be uploaded to the course group.

Page 41: Class 8 - Database Programming

AssignmentUsing the employees table, write a PHP code snippet that does the following:1- Shows all the entries in the table. 2- Deletes an entry.3- Edits an entry.4- Adds a new entry.

The resulting application should look like PHPMyAdmin interface.

Page 42: Class 8 - Database Programming

What's Next?• Course Project and Performance tips & best practices

Page 43: Class 8 - Database Programming

Questions?