08/09/2015 intro php & mysql 1 helen hastie [email protected] room: em2.44 material available on...

28
23/06/22 Intro PHP & MySQL 1 Helen Hastie [email protected] Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction to Database Systems Accessing MySQL database via PHP - 2

Upload: emil-hubbard

Post on 26-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 1

Helen [email protected]

Room: EM2.44Material available on Vision (modified from slides by Monica Farrow)

F27DB Introduction to Database SystemsAccessing MySQL database via PHP - 2

Page 2: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 2

Recap

•Website design

Choices

Request spy details(Enter code)

Spy detailsdisplayed

Update spy (enter details)

Changes confirmed

Enter new spy(enter details)

Add confirmed

Login

Covered in lecture 5

Page 3: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 3

Recap - sessions

• Sessions are visits to a website• PHP provides functions for managing

sessions• Use session_start() before outputting any html

• Session variables are used to store and retrieve session data• E.g. Adding a session variable

$_SESSION[‘password’]=$_POST[‘password’];

• E.g. Retrieving a session variable $password = $_SESSION[‘password’];

• A session ends when the user moves away from the site, or it can time-out

Page 4: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 4

Recap - Display spy - response

• Links to other actions• One table for the Spy data• Another for the skills

• To keep things simple,I am using the columnname from the databaseas headings• Not ideal!

Page 5: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 5

Recap : dbfunctions.php file

• This file contains my own functions to run each of the mysql database functions, and also to automatically display a table• This makes the code in the main script easier

to read• Instead of lots of blocks of code ‘do this, then see if it

works’ one after the other, you see simpler code, shown on the next slide

• It means that beginning programmers can use my example php scripts, and only change

• Their username• the SQL queries• the parameters from the form, which are needed for

the SQL query

Page 6: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 6

Creating the form to add a spy

• Mostly html here •heading•Links•Input fields

Page 7: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 7

Error prevention

• For gender, use radio buttons to ensure that only valid options are entered

• Use php scripts to get values from MySQL for drop-down list and the multiple option box• The php scripts query

the database to find out the existing spymasters and skills

Page 8: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 8

Creating the SpyMaster option list

• Retrieve username and password from session variables

• Connect to database• Run query to find all spymaster

codenames• 'SELECT mCodeName FROM SpyMaster';

• Create html option list from that//find all the spymaster codenames$query = 'SELECT mCodeName FROM SpyMaster';$result = runQuery($query);

//now need to display in option box - pto

Page 9: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 9

Display spymaster options

//PUT EACH SPYMASTER CODENAME INTO AN OPTION BOX //first print out blank initial option print '<select> <option value = ""> </option>'; //get each row in turn while ($row = mysql_fetch_row($result) ) { //get value of first (only) column in the row //and place as value and display in option

print '<option value="' . $row[0 ]. '">' . $row[0] . '</option>'; } print '</select>';}

Page 10: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 10

Display skill options

• Very similar to the spymaster code• The skill name is value displayed for the user to

choose• The skill code is the value to be sent to the next

script• A multiple option box is created which returns all

selected items in an array//option value is code, but name is displayed$query = "SELECT skillCode, skillName FROM SpySkillList";$result = runQuery($query); print '<select name = "skill[]" multiple>';while ($row = mysql_fetch_row($result) ){

print '<option value="' . $row[0 ] . '">' . $row[1] . '</option>';}print '</select>';

Page 11: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 11

Receiving the data

• The script referred to in the form’s action attribute, which generates the response, must:• Start a session & retrieve username and

password• Output initial html• Pick up all the form parameters• Create an INSERT command with all the

parameters• Run it• Report whether it worked or not

Page 12: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 12

Creating the insert command

• Picking up the form parameters• Creating the INSERT command

• Notice outer double quotes, inner single quotes

• It’s probably a good idea to test this out at this stage, just printing the insert command to make sure it looks alright, before trying to run it

//First pick up the parameters //from the form $spycode = $_POST["codename"];$firstName = $_POST["first"];Etc etc//define and run the insertion$query = "INSERT INTO Spy VALUES ('$spycode', '$firstName', '$lastName', '$date', '$gender', '$mark', 0, '$spymaster', NULL )";print $query . "<br/>"; /

Page 13: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 13

Inserting the spy

$insResult = mysql_query($query);if ($insResult) print("Spy details for " . $firstName . " " . $lastName . " have been inserted<br/>");

else//vital to know why it failed

exit ( $query. " " . mysql_error(). "</p></body></html>");

• Run it using the function mysql_query and test to see whether it worked

• Print whether the insertion was a success or not. Exit if not.

Page 14: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 14

Inserting the skills

• A new record must also be created in the SpyWithSkill table, for each skill in the skill array parameter• Consists of the spy code and the skill code

$skills = $_POST['skill'];foreach($skills as $skill) //for each skill{ $query = "INSERT INTO SpyWithSkill VALUES ('$spycode', $skill)"; print $query . '<br/>'; $insResult = mysql_query($query); if ($insResult) { print("Spy skill inserted<br/>"); } else exit ( mysql_error(). "</p></body></html>" );

Page 15: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 15

Problems with insertions

• What sort of things can go wrong with insertions?• Duplicate Primary Key

• A record already exists with this primary key

• Foreign key invalid• No matching value exists in the referenced table

• Invalid data• Incorrect range, incorrect data type, incorrect length

Page 16: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 16

Insertion error prevention / feedback

• Today’s example just prints out the mysql error message, which wouldn’t be very friendly for a user• It would be better to determine what is wrong

and output a suitable message for the user

• Frequently javascript is used in the HTML form to ensure that the data is acceptable• Not covered in this module• It may be that the user’s computer has

javascript disabled or otherwise not functioning• So ideally all these values should be checked in the

PHP script too

Page 17: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 17

Running an update command

• Updates work exactly like insertions• Gather the data via a form and post to a php

script• Create an UPDATE command in PHP, using

parameter data• Run the Update command• Check that it worked and output feedback

Page 18: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 18

Dates

• To insert a date to MySQL, we need it in the format YYYY-MM-DD• E.g INSERT INTO MyTable

VALUES ( …, …, …, ‘2008-12-04’,…,…);

• To insert today’s date, you can use the MySQL CURDATE() function:• E.g. INSERT INTO MyTable

VALUES ( …, …, …, CURDATE(),…,…);• You can also use CURRENT_DATE() which is a

synonym for CURDATE()

Page 19: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 19

PHP, objects and extensions

• PHP can be used in a ‘procedural’ way, as here• work your way through the lines of code, use

functions to reduce code duplication and simplify the main script

• However recent versions also allow object-oriented programming and exception handling• Not covered in this module• You may see examples of this on the web or in

books

Page 20: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 20

Beyond MySQL and PHP

• A brief look at wider issues• Dynamic and static web pages• Connecting to a database from a programming

application• Programming and SQL• Interoperability

Page 21: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 21

Static and dynamic web pages

• Some web pages are static• The html never changes. These pages can be

written entirely in html.• Examples are the Request Spy Details page, &

initial Log-in page

• Many web pages are dynamic• Some of the html never changes• Some is determined at run-time, and depends

on the request. This usually involves the submission of data from html forms, and connection to a database to query or update records

• Suitable software includes PHP & MySQL

Page 22: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 22

Querying and updating a database

• The process is the same for all databases and server-side languages• Submit a request, probably with data in

parameters• Using a script or programming language

• Connect to the database• create SQL command including this data• Submit the command to the database• Process the result obtained from the database• Output the response, consisting of appropriate html,

which may contain data from the database

Page 23: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 23

Connecting to the database

• There are different databases and different scripting languages• How to know how to connect?

• The ODBC standard, pioneered by Microsoft, is an Open Database Connectivity standard• Aims to be independent of database, programming

language or operating system

• There are ODBC drivers for most DBMS • It may be necessary to locate/install these

• ODBC forms the basis of other connectivity such as JDBC (java connectivity) and OLE-DB (later Microsoft version)

Page 24: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 24

ODBC Architecture : 4 levels

• The application uses a driver to submit SQL statements and retrieve results.

• The driver manager helps the application find a driver.

• The driver translates the application's data queries into commands that the DBMS understands. Both the application and the DBMS must be ODBC-compliant -- that is, the application must be capable of issuing ODBC commands and the DBMS must be capable of responding to them

• A data source is a collection of data (usually a database) which the driver can query.

Application

Driver Manager

Driver Driver Driver

Data Source

Data Source

Data Source

Page 25: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 25

SQL and programming

• SQL alone is insufficient for an application• Need some type of programming language to

deal with logic (alternatives, repetition)

• Some DBMS have included programming functionality as an extension of SQL• An example is Oracle’s PL/SQL• Includes loops and conditional statements• Procedures, functions and triggers can be

created and stored within the database• A good solution for SQL intensive applications

• For applications which are logic-intensive, SQL can be included within a programming language - pto

Page 26: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 26

Programming SQL

• A database can be accessed from a programming language in one of two ways:

• Embedded SQL (not covered)

• directly embedding SQL statements in the program source.

• A precompiler is required to replace SQL statements with calls to DBMS routines.

• A Database Connectivity API, like ODBC or JDBC (how PHP accesses MySQL)

• a standard set of functions in the language that access the database, using hidden 'compiler magic'.

• Avoids the need for precompilation and is more portable – but involves more use of Strings

Page 27: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 27

Interoperability?

• Relational systems with SQL provide a single model for data and so should provide good support for such general application development (one application, easy to alter the database)

• But:• the programming interface to SQL varies• the functionality provided varies• the flavour of SQL varies• the system catalog varies - e.g. domain names• some data is not in a database• DBMS vendors pride themselves on adding extra

functionality

Page 28: 08/09/2015 Intro PHP & MySQL 1 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction

19/04/23 Intro PHP & MySQL 28

The MySpy website

• My Spies website is available for downloading on the module website• Download it, put into your www folder, and play

with it using a URL like http://www2.macs.hw.ac.uk/~username/IntroDB/Spies/SpyStart.html

• You can then take another copy and adapt it for use in your coursework, rather than starting from scratch, although you can also do this if you prefer!

• NOW INCLUDES Insert example page too