Sq m."> Sq m.">
Download presentation
Presentation is loading. Please wait.
Published byThomas Baldwin Modified over 9 years ago
1
02/09/2015 Intro PHP & MySQL 1 Helen Hastie h.hastie@hw.ac.uk Room: EMB244 Material available on Vision (modified from slides by Monica Farrow) F27DB Introduction to Database Systems Accessing MySQL database via PHP - 1
2
02/09/2015 Intro PHP & MySQL 2 lawn_length = 2.1 lawn_width = 10 XHTML containing form XHTML SERVER HTML PAGE PHP SCRIPT receives form data processes it outputs HTML Recap - Using PHP to process form data and reply CLIENT
3
02/09/2015 Intro PHP & MySQL 3 Recap - PHP script Displaying the lawn area The area is <?PHP $width = $_POST["lawn_width"]; $length = $_POST["lawn_length"]; print $width*$length; ?> Sq m.
4
02/09/2015 Intro PHP & MySQL 4 Spy Website design Pages in green with italics need to know about username and password Login stores the username and password The response pages query or update the database The ‘enter’ page reads the DB to get values for pull-down lists Request spy details (enter code) Request update spy (enter details) Response: Changes confirmed Request Enter new spy (enter details) Response: Add confirmed Login Choices Response: Spy details displayed
5
02/09/2015 Intro PHP & MySQL 5 Remembering data One big problem is that after the response to a request is sent, HTTP closes the connection Each request is treated as an independent connection, with no relationship to any preceding requests/responses However, when a user visits a website, there are various reasons for wanting to remember about this user throughout their visit In our case, remembering a username and password entered at the start to allow connection to the mysql database in any page
6
02/09/2015 Intro PHP & MySQL 6 Sessions A session is ‘The sequence of HTTP transactions generated when a user visits a website and browses through the pages of that site. The session terminates when the user leaves the site.’ A session could also be referred to as a visit
7
02/09/2015 Intro PHP & MySQL 7 Session Management - theory Commonly a middleware language such as PHP will provide methods for storing session data on the server It does this by allocating each individual session a unique session ID, which is sent between responses and requests. The session ID is stored in your computer’s memory and not written to your hard drive. It is only stored for the duration of your session, and it is automatically deleted after you leave the domain. This ID is used on the server side to identify data stored for that session
8
02/09/2015 Intro PHP & MySQL 8 lawn_length = 3 lawn_width = 4 XHTML containing form SERVER HTML PAGE PHP SCRIPT receives form data processes it outputs HTML Sessions in PHP – example CLIENT PHP SCRIPT receives form data processes it outputs HTML XHTML Session variable ID, length XHTML & Session ID
9
02/09/2015 Intro PHP & MySQL 9 Session ID on the server-side - theory Anything that needs to kept for the duration of the session is stored in session variables These session variables are associated with the ID for that session, so they can be retrieved E.g. Username and password Parts of an order Which adverts have been seen
10
02/09/2015 Intro PHP & MySQL 10 End of a session - theory All the data for a particular session is destroyed at the end of the session Either when the user logs out Or when the php script has been written to explicitly destroy the session using session_destroy() Or when the session ‘times out’ : possibly 15 minutes with no activity
11
02/09/2015 Intro PHP & MySQL 11 Sessions in PHP - practice PHP provides functions to manage sessions We use the these functions Behind the scenes, a session ID is associated with each session. The user doesn’t need to know about it. You will need to use this php function: session_start(); It’s very important to put the call to this function near the start of every script that uses session variables, before you output any html at all. You need to store any data that you want to keep for the whole session in the $_SESSION associative array i.e. username and password
12
02/09/2015 Intro PHP & MySQL 12 Session variables - practice Use the associative array $_SESSION to store and retrieve data (similar to the $_POST array but make up your own keynames) Elements identified by key/value pairs You can add many elements to this array by specifying the key and the value E.g. Adding a session variable in one script $_SESSION[‘password’]=$_POST[‘password’] ; E.g. Retrieving a session variable in a later script $password = $_SESSION[‘password’];
13
02/09/2015 Intro PHP & MySQL 13 Summary Sessions are visits to a website PHP provides functions for managing sessions Session variables are used to store and retrieve session data A session ends when the user moves away from the site, or it can time-out
14
02/09/2015 Intro PHP & MySQL 14 Login page This page is an html form There is a special input type for passwords After submit, the username and password are sent to a php script
15
02/09/2015 Intro PHP & MySQL 15 Receiving the username and password The receiving php script starts the session then stores the username and password into session variables The rest of the page is output in html <?php //display all errors error_reporting(E_ALL); ini_set('display_errors', 1); //start session session_start(); //store username and password for later $_SESSION['username'] = $_POST['username']; $_SESSION['password'] = $_POST['password']; ?> <!DOCTYPE html... Lots of html
16
02/09/2015 Intro PHP & MySQL 16 Requesting to View a spy Links to other action(s) Enter codename of spy you want to see the details of This is an HTML form On submit, the codename is sent to a php script.
17
02/09/2015 Intro PHP & MySQL 17 Body of the html – the request Add a spy view a spy Enter codename of the spy you wish to know about:
18
02/09/2015 Intro PHP & MySQL 18 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 column name from the database as headings Not ideal!
19
02/09/2015 Intro PHP & MySQL 19 Finding the spy details – the response The PHP script generating the response must Ask for errors, start the session Output the initial html Retrieve username and password from session variables and connect to the database Get hold of the Spy codename from the form parameters $codename = $_POST[“codename”]; Search the database for the spy with that codename Output an html table showing column headings and the data found Search the database for the spy’s skills Output an html table showing column heading and the skills found Output the rest of the html.
20
02/09/2015 Intro PHP & MySQL 20 Body of spy display page Spies. Add a spy Update Spy Payment View one spy View a Spy Spy with codename = bud codeName bud firstName Fanny Etc...... Most of this page stays the same for all spies However, data in red italics comes from the database and (except for column names) is different for each spy.
21
02/09/2015 Intro PHP & MySQL 21 DisplayOneSpy.php - 1 The php script Starts with 2 lines asking for errors to be reported Continues by naming another php file whose contents we want to include I have put all the database interaction into a separate php file consisting of useful db functions. This simplifies the code in the main script and avoids repetition <?php error_reporting(E_ALL); ini_set('display_errors', 1); include ("dbfunctions.php");
22
02/09/2015 Intro PHP & MySQL 22 DisplayOneSpy.php - 2 The php script Continues by starting the session This MUST come before any html at all is output //start session session_start();
23
02/09/2015 Intro PHP & MySQL 23 DisplayOneSpy.php - 3 The php script Continues by outputting all the start html End PHP tag, then some html, then start php tag ?> <!DOCTYPE html... A lot of html... View a Spy <?php
24
02/09/2015 Intro PHP & MySQL 24 DisplayOneSpy.php - 4 The php script Continues by retrieving the username and password from the session variables //retrieve username and password $username = $_SESSION['username']; $password = $_SESSION['password'];
25
02/09/2015 Intro PHP & MySQL 25 PHP and database PHP provides database functions such as Connect to the database management system Select the database Run a query Look at the results Was the insert/ delete/update successful? How many rows were returned from a SELECT query? What are the contents of these rows? Provide error information if it didn’t work PHP provides these functions for many different databases. The ones for MySQL start with ‘mysql’
26
02/09/2015 Intro PHP & MySQL 26 Connecting to mysql 1 For every php command using mysql, we need to run it, and then check that it worked If it failed, need to print a useful message and then finish the html off tidily before stopping //use mysql function to connect $dbConn = mysql_pconnect ("anubis", $username, $password) ; if (!$dbConn ) //if it didn’t work { //print error message and end html, exit script print " Cannot connect to database - check username and password "; print mysql_error()." "; print " "; exit(); } This is part of the dbfunctions.php file
27
02/09/2015 Intro PHP & MySQL 27 If you can’t connect to the database If the script can’t connect to the database, there is either something wrong with your code or something seriously wrong with the database connection When you are developing your code, you want to see details of errors, because the problem is probably with your code My error message on the last slide gives this info. When your application is ‘live’, you should change it to output a nice message to the user E.g. ‘There is a problem with the database connection. Please try again later’
28
02/09/2015 Intro PHP & MySQL 28 The 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 It means I can use these functions in any of my pages, and only write the scripts once It means that beginning programmers can use my example php scripts, and not change much. E.g.: the SQL queries the parameters from the form, which are needed for the SQL query
29
02/09/2015 Intro PHP & MySQL 29 Connecting to the database The DisplayOneSpy.php script continues, using the following functions in the dbfunctions file dbConnect, dbSelect runQuery (next page) //connect to mysql //using retrieved username and password //(see slide 24) dbConnect("$username", "$password") ; //select your own database dbSelect("$username");
30
02/09/2015 Intro PHP & MySQL 30 DisplayOneSpy.php Creating the query I suggest that you write the query and run it in MySQl first, to make sure it works Then include it in your PHP script as shown below, using a form parameter in the WHERE clause MAKE SURE YOU INCLUDE A SPACE BETWEEN LINES i.e. ‘Spy WHERE’ not ‘SpyWHERE’ //create query $codename = $_POST['codename']; $query = "SELECT * FROM Spy WHERE codeName= '$codename'"; //run query $result = runQuery($query);
31
02/09/2015 Intro PHP & MySQL 31 Running the query The runQuery function function runQuery($query) { $result = mysql_query($query); if ($result) { //print($query. " "); return $result; } else { //don't come here unless program logic error //or some other problem with the database print $query. " ". mysql_error(). " "; print " "; exit("Bye"); }
32
02/09/2015 Intro PHP & MySQL 32 The results from a SELECT query If the query didn’t work, the runQuery method prints details and exits the script. Likely errors here: Your SQL command is incorrect (wrong syntax, or wrong table or column names) If the query returns 0 rows It has worked successfully There just aren’t any results to match what you asked for Either there really aren’t any. Maybe the codename was mistyped. Or you didn’t ask for what you should have asked for!
33
02/09/2015 Intro PHP & MySQL 33 DisplayOneSpy.php - 0 rows If no rows are returned, you need to check for this and write a sensible message to the user. There is a MySQL function to find the number of rows //run query $result = runQuery($query); $numrows = mysql_num_rows($result); if ($numrows == 0) { print "No spy with codename = $codename"; print " "; exit(); }
34
02/09/2015 Intro PHP & MySQL 34 DisplayOneSpy.php – some results The heading includes the codename searched for (obtained from the form parameter) The file dbfunctions includes a function ‘displayVertTable’ from the query result It creates a table from the column names and the data //run query $result = runQuery($query); //check there are some rows... //print table of results print " Spy with codename = $codename "; displayVertTable($result);
35
02/09/2015 Intro PHP & MySQL 35 What we want codeName bud firstName Fanny Etc......
36
02/09/2015 Intro PHP & MySQL 36 Creating the table Inside the displayVertTable function //set up table print ' '; //find how many fields (columns) $fieldCount = mysql_num_fields($result); $row = mysql_fetch_row($result); //for each field, print column name and data for ($i=0; $i<$fieldCount; $i++) { print (" "); $fieldName = mysql_field_name($result, $i); print " ".$fieldName." "; print (" ". $row[$i]. " ") ; print " "; } print (" "); This is part of the dbfunctions.php file
37
02/09/2015 Intro PHP & MySQL 37 Displaying your own table In this module, you are welcome to use the displayVertTable function For those who are keen programmers, and for serious websites Obviously it is not ideal to display the column names as headings for the user no spaces in the text! You could write your own display for each table, choosing better headings
38
02/09/2015 Intro PHP & MySQL 38 Displaying the skills Just as before, define the query and run it There is another function in dbfunctions.php called ‘displayTable’ which displays column names across the top then rows of data //display skills print " Skills "; $query = "SELECT skillName FROM SpySkillList L, SpyWithSkill W WHERE L.skillCode = W.skillCode AND W.spyCode = '$codename'"; $result = runQuery($query); displayTable($result);
39
02/09/2015 Intro PHP & MySQL 39 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/S pies/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!
40
02/09/2015 Intro PHP & MySQL 40 Next few weeks Week 6 (this week) Monday – Lecture and lab as usual Wed – no lecture: work on the assignment Week 7 (next week) Monday- Double lab Wednesday Lecture: Continuing with MySQL and PHP- how to insert a record into the database from an html form Week 8 Monday- Double Lab Wednesday Continuing with MySQL and PHP
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.