1 / 37

A Web-Based Introduction to Programming

A Web-Based Introduction to Programming. Chapter 12 Associative Arrays. Intended Learning Outcomes. Summarize key characteristics of associative arrays. Create an associative array. Identify useful applications for associative arrays.

williamsonj
Download Presentation

A Web-Based Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A Web-Based Introduction to Programming Chapter 12 Associative Arrays Chapter 12

  2. Intended Learning Outcomes • Summarize key characteristics of associative arrays. • Create an associative array. • Identify useful applications for associative arrays. • Use a literal key value to access a value in an associative array. • Use a variable that contains a key value to access a value in an associative array. • Describe the structure of the PHP $_POST array. • Summarize the basic characteristics of a Web session • Create and destroy a Web session. • Use the $_SESSION array to share variables between pages Chapter 12

  3. Introduction • Chapter 11 demonstrated the structure and use of arrays that are indexed with numerical values. • Many languages, including PHP, also permit the use of associativearrays… Chapter 12

  4. Associative Arrays • An associative array is indexed with character strings (keys) that describe the content of each element (values). For example: $scores['Exam 1'] = 90; $scores['Exam 2'] = 93; $scores['Exam 3'] = 87; $scores['Essay'] = 78; $scores['Project'] = 80; • In the first element, 'Exam 1' is a key, 90 is a value. Chapter 12

  5. Associative Arrays • Associative Arrays are especially useful for lookups.. • Associative arrays have limited uses. They are only useful when: • Meaningful key names can be provided for each array element. • The array contains a relatively small number of values. Chapter 12

  6. Looking up a Value Using a Key We can use an associative array as a lookup by referencing a particular array key, for example to lookup a user password from an array where the keys are user IDs: $userList ['mike75'] = "abc123"; $userList ['mary2'] = "xyz999"; $userList ['chris17'] = "abc999"; print("<p>The password for user chris17 is $userList['chris17']</p>"); Chapter 12

  7. Using a Variable to Reference a Key Value It is often useful to use a variable to look up an array value. For example we can obtain a user ID from an HTML form and use this as the key to test the user password in the $userList array: $userList ['mike75'] = "abc123"; $userList ['mary2'] = "xyz999"; $userList ['chris17'] = "abc999"; $id = $_POST['id'] ; $password = $_POST['password '] ; if ($userList ['$id'] == $password) print("<p>WELCOME $id!</p>"); else print("<p>YOUR LOGIN FAILED</p>"); Chapter 12

  8. Another Example: Company Information • Using an associative array to store important company information $companyInfo ['name'] = "Most Excellent Web Design, Inc."; $companyInfo ['street'] = "123 Main Street"; $companyInfo ['city'] = "Sometown"; $companyInfo ['state'] = "SomeState"; $companyInfo ['zip'] = "12345"; $companyInfo ['email'] = "excellent@mewd.com"; $companyInfo ['phone'] = "(123) 456-7890"; $companyInfo ['fax'] = "(098) 765-4321"; Chapter 12

  9. Another example: Countries and Capitals $capitals['FRANCE'] = "PARIS"; $capitals['ENGLAND'] = "LONDON"; $capitals['AFGHANISTAN'] = "KABUL"; $capitals['ANGOLA'] = "LUANDA"; $capitals['BOLIVIA'] = "SUCRE"; $country = $_POST[‘country']; print("<p>The capital of $country is $capitals[$country]</p>"); Chapter 12

  10. Using the array() Function to Create Associative Arrays • The PHP array() function can be used to create associative arrays using the => operator to associate keys and values: $capitals = array ('FRANCE' => "PARIS", 'ENGLAND' => "LONDON", 'AFGHANISTAN' => "KABUL", ‘ANGOLA' => "LUANDA“, 'BOLIVIA' => "SUCRE"); • This is equivalent to assigning each array element separately (previous slide) Chapter 12

  11. More About the $_POST Array • PHP defines a number of standard associative arrays. • Identified by $_ at the beginning of the array name. • The $_POSTarray is an example. • When a user submits a form using method = "post" attribute, a $_POST array is created for the program that will process the form. • The keys of the $_POST array are the names associated with each input field in the form • The values in the $_POST array are the valuessubmitted by the user in these fields. Chapter 12

  12. More About the $_POST Array • Example: <form action = "wage2.php" method = "post" > <p>Please enter your hourly wage: <input type = "text" size = "20" name = "hourlyWage" /></p> <p>And the hours you have worked: <input type = "text" size = "20" name = "hoursWorked" /></p> <input type = "submit" value = "Wage Report " /> </form> Chapter 12

  13. More About the $_POST Array • The method is "post" so the server provides wage2.php with a $_POST array with the values submitted by the user. • Each value in the $_POST array is indexed with the names from the HTML form fields: • $_POST ['hourlyWage']contains the value submitted by the user in the field named "hourlyWage".  • $_POST ['hoursWorked']contains the value submitted by the user in the field named "hoursWorked". Chapter 12

  14. More About the $_POST Array • Our code examples always retrieve values from the $_POSTarray and store them in program variables: $hourlyWage = $_POST['hourlyWage']; $hoursWorked = $_POST['hoursWorked']; $pay = $hourlyWage * $hoursWorked; • But we can also use the elements of the $_POST array directly without any need for additional variables: $pay = $_POST['hourlyWage'] * $_POST['hoursWorked']; Chapter 12

  15. The $_GET and $_REQUEST Arrays • The $_GETarray is used when the method attribute of the HTML <form> tag is assigned the value "get". • Less secure (values are submitted as part of the URL). • Limits the number of characters that can be submitted. • The $_REQUESTarray will receive form values whether the <form> attribute is "get" or "post". • Good choice when a program handles input from multiple sources, where it may not be known whether the input is submitted using the "get" or "post" method. Chapter 12

  16. Using the isset() Function • The isset() function tests whether or not a variable has already been created. if(isset($someVariable)) • This is not the same as the empty() function: if(empty($someVariable)) • The empty() function tests whether or not a variable contains a value, the isset() function tests whether or not the variable exists. Chapter 12

  17. Using the isset() Function to Process HTML Forms • The isset() function can be used to combine an HTML form with the code to process the form on the same page. • For example if an HTML form contains a text input named 'age', you can test whether or not this element exists in your $_POST array: if(isset($_POST['age'])) • This will indicate whether or not a form containing 'age' has been submitted. Chapter 12

  18. Using the isset() Function to Process HTML Forms • By testing if $_POST contains values, a page can choose to display or process the form: if (isset($_POST['age'])) { // statements to process this form } else { // display the form } Chapter 12

  19. CODE EXAMPLE:addTwoImproved.php Chapter 12

  20. CODE EXAMPLE:addTwoImproved.php if (isset($_POST['number1'])) { $number1 = $_POST['number1']; $number2 = $_POST['number2']; $result = $number1 + $number2; print ("<h1> RESULTS </h1>"); print (" <p>$number1 + $number2 = $result.</p> "); print (" <p><a href = \"addTwoImproved.php\"> Return to the Input Form</a></p> "); } // See next slide for the ELSE section.. Chapter 12

  21. CODE EXAMPLE:addTwoImproved.php // continues from previous slide else { print ("<h1>ADD TWO NUMBERS</h1> <form action = \"addTwoImproved.php\" method = \"post\" > <p>1st number: <input type=\"text\" size=\"20\“ name=\"number1\" /></p> <p>2nd number: <input type=\"text\" size=\"20\" name=\"number2\" /></p> <p><input type = \"submit\" value = \"Tell me the sum\" name = \"submit\" /></p> </form>"); } Chapter 12

  22. Web Sessions and the $_SESSION array • A Web session allows data to be maintained beyond the life of a single Web page. • The data can be accessed and modified by multiple pages, as long as the session is running. • In PHP, a Web session is started using session_start(), and ended using session_destroy(). • A session also ends if the user closes all open windows of the browser. • The data for the session is stored in a standardassociativearray named$_SESSION. • Each user's data is maintained separately. Chapter 12

  23. Associating Web Pages with a Session • Everypage (not just your intended starting page) mustinclude a call to start_session() in a PHP section • This statement must appear beforeany HTML tags that appear in the file: <php session_start(); ?>  <html> ... HTML and additional PHP code here..  </html> Chapter 12

  24. Working with Session Variables • Elements can be added to the $_SESSION array whenever needed, just like any other array: $_SESSION['playerName'] = $_POST['playerName']; $_SESSION['playerScore'] = 0; • $_SESSION elements can be accessed and modified by any page that includes a call to session_start(), for example: print ("<h1>PLAYER: ".$_SESSION['playerName']."</h1>"); $_SESSION['playerScore'] = $_SESSION['playerScore'] + 10; Chapter 12

  25. Ending the Session • Use the session_destroy()function. All session data is lost at this time. • If the user returns to a page that includes a call to the session_start()function, after the session has been ended, a new session will be created at that time. • The session will also end if the user closes all of their browser's open windows. Chapter 12

  26. A Simple Example: Raffle • Look at the following three files in the sessions folder, located in your samples folder: raffle.html, raffle.php, choosePrize.php. • To submit a raffle ticket number open raffle.html. Chapter 12

  27. Raffle Screenshots Chapter 12

  28. Raffle Screenshots Chapter 12

  29. Coding Raffle • Review the Raffle application code carefully • Note how the player’s name and city are stored in the $_SESSION array so these values can be accessed by choosePrize.php. • Note that all pages use session_start() to participate in the session. • Note that choosePrize.php includes session_destroy() to end the session. Chapter 12

  30. A Small Game Example: Goldhunter • Look at the following three files in the sessions folder, located in your samples folder: goldHunter.html, goldHunter1.php, goldHunter2.php. • To play the game open goldHunter.html. Complete the game to destroy the session. • Try playing without entering a user name. • Try starting the game by opening goldHunter1.php or goldHunter2.php instead of goldHunter.html Chapter 12

  31. GoldHunter Screenshots Chapter 12

  32. GoldHunter Screenshots Chapter 12

  33. Another Session Example: Online Quiz (tracks the score) • Open mathProblem.php in the sessions folder: Chapter 12

  34. Managing a Web Session:It Takes a Lot of Planning! • It takes a lot of planning to design a Web session. • You will probably need a lot of selection structures. • Your code must allow for: • Any events that are included in the session. • Unexpected user actions. • For example, what if the user returns to the session's first page, and this page resets their score to 0, or goes directly to a page that assumes the user has previously entered their name on another page? • Your code should handle all possible user actions.. Chapter 12

  35. Managing a Web Session: The isset() Function • Recall that the isset()function tests whether or not a variable has already been created. • This is useful to decide what action should be taken on a Web page. • To set the score to 0 only once in a session: if (!isset($_SESSION['playerScore'])) $_SESSION['playerScore'] = 0; • To ensure the user has already provided a name: if (!isset($_SESSION['playerName'])) print("<a href=\"start.php\">Go to start page</a>"); Chapter 12

  36. A Note About Session Security • When a user opens a Web page that initiates a session, the Web server creates a unique identification (UID) number for the session. • Although many users might access the Web application at the same time, the server uses the UIDs to distinguish between each user’s session. • The data for each user is automatically maintained in a separate $_SESSION array associated with the user's UID. Chapter 12

  37. Chapter 12

More Related