F27DB Introduction to Database Systems Accessing MySQL database via PHP - 2 Helen Hastie hhastie@hw.ac.uk Room: EM2.44 Material available on Vision (modified from slides by Monica Farrow) 23/03/2016 Intro PHP & MySQL 1 Recap •Website design Login Covered in lecture 5 Request spy details (Enter code) Spy details displayed 23/03/2016 Choices Enter new spy (enter details) Add confirmed Intro PHP & MySQL Update spy (enter details) Changes confirmed 2 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 23/03/2016 Intro PHP & MySQL 3 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 column name from the database as headings • Not ideal! 23/03/2016 Intro PHP & MySQL 4 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 23/03/2016 Intro PHP & MySQL 5 Creating the form to add a spy • Mostly html here • heading • Links • Input fields 23/03/2016 Intro PHP & MySQL 6 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 23/03/2016 Intro PHP & MySQL 7 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 23/03/2016 Intro PHP & MySQL 8 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>'; } 23/03/2016 Intro PHP & MySQL 9 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>'; 23/03/2016 Intro PHP & MySQL 10 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 23/03/2016 Intro PHP & MySQL 11 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/>"; / 23/03/2016 Intro PHP & MySQL 12 Inserting the spy • 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. $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>"); 23/03/2016 Intro PHP & MySQL 13 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>" ); 23/03/2016 Intro PHP & MySQL 14 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 23/03/2016 Intro PHP & MySQL 15 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 23/03/2016 Intro PHP & MySQL 16 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 23/03/2016 Intro PHP & MySQL 17 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() 23/03/2016 Intro PHP & MySQL 18 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 objectoriented programming and exception handling • Not covered in this module • You may see examples of this on the web or in books 23/03/2016 Intro PHP & MySQL 19 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 23/03/2016 Intro PHP & MySQL 20 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 23/03/2016 Intro PHP & MySQL 21 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 • • • • • 23/03/2016 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 Intro PHP & MySQL 22 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) 23/03/2016 Intro PHP & MySQL 23 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. 23/03/2016 Intro PHP & MySQL Application Driver Manager Driver Driver Driver Data Data Data Source Source Source 24 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 23/03/2016 Intro PHP & MySQL 25 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 23/03/2016 Intro PHP & MySQL 26 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 23/03/2016 Intro PHP & MySQL 27 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! • NOW INCLUDES Insert example page too 23/03/2016 Intro PHP & MySQL 28