Enter your Sign on user name and password.

Forgot password?
  • Follow us on:

Professor Matthew M.'s Advanced PHP with MySQL course continues from his Introduction to PHP course but is also appropriate for those already well versed in PHP. Matthew again focuses on topics relevant to developers and works on real code in text editors as well as executing MySQL commands from the command prompt. A working web application program will also be developed throughout the course to build on new concepts learned. Topics covered include reading/writing files, object-oriented programming, cookies, MySQL databases, and MySQL commands. Downloadable code and homework solutions are included so students can follow along with the lessons.

Loading video...
expand all   collapse all
I. Advanced PHP with MySQL
  Course Introduction 13:36
   Intro 0:00 
   Advanced PHP w/ MySQL 0:13 
    Course Introduction 0:14 
    Course Content 0:59 
   Web Application: Educator Store 1:45 
    Web Application: Educator Store 1:46 
   Object-Oriented Programming 6:09 
    Object-Oriented Programming Overview 6:10 
   MySQL 6:50 
    MySQL Overview 6:51 
    Example: Command Prompt & MySQL 8:34 
   What You Will Learn 9:34 
    What You Will Learn 9:35 
   Course Prerequisites 11:52 
    Course Prerequisites 11:53 
  Advanced Course Development Environment 18:46
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Development Environment Setup 1:36 
    Firefox Web Browser, XAMPP, and PSPad Text Editor 1:37 
   Course Directory Structure 4:36 
    Course Directory Structure 4:37 
   phpDocumentor 7:23 
    phpDocumentor Overview 7:24 
    Parsing Source Code 7:44 
    docs Subdirectory 9:06 
    Asvanced PHP Course Documentation Example 10:21 
   Previous Educator PHP Students 14:14 
    Lib Directory Changes 14:38 
    Images Directory Changes 14:57 
    VERSION Constant 15:40 
    Comments Noting a Specific Version Number 17:04 
   Homework Challenge 17:30 
    Homework Challenge 17:31 
  Introduction to File I/O 35:37
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   File I/O 1:34 
    File I/O Overview 1:35 
    Performing file I/O: 3 Steps 1:52 
   File Permissions 2:28 
    Read Permission & Write Permission 2:29 
   fopen() 4:47 
    fopen() 4:48 
    Two Required Parameters 5:01 
    Successful fopen(): File Handle and Resource 5:21 
    FALSE and E_WARNING Error 6:00 
    Example 6:39 
   File Paths 7:10 
    File Paths 7:11 
   File Access Modes 9:18 
    File Access Modes 9:19 
   Coding Example: fopen() 10:31 
    Using Relative and Absolute Path & Non-Existent File 10:32 
   File Pointers 15:55 
    File Pointers 15:56 
    Example File 16:11 
    Opening a File with fopen() Using 'r' as the Access Mode 16:22 
   fgets() 17:55 
    fgets() Overview 17:56 
    Coding Example: fgets() - Reading a Line at a Time 18:26 
   feof() 20:10 
    feof() Overview 20:09 
    Coding Example: feof() 20:50 
   fclose() 23:43 
    fclose() Overview 23:44 
    Coding Example: fclose() 25:02 
   Coding Example: Current Stock 26:10 
    Coding Example: Current Stock 26:11 
   trim () 31:39 
    trim () Overview and Example 31:40 
   Homework Challenge 33:35 
    Homework Challenge 33:36 
  Web Application Development 36:36
   Intro 0:00 
   Lesson Overview 0:16 
    Lesson Overview 0:17 
   Version 1.0 Changelog 0:31 
    catalog.php 0:32 
    Function Library: fileLIB.php 5:00 
   Version 1.1 Changelog 27:12 
    createItemDataArray() and createDeptDataArray() 27:13 
    outputSimpleItemLink() and outputSimpleDeptLink() 32:06 
  HTTP & the POST Method 34:36
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   HTTP Model 1:28 
    HTTP Model 1:29 
    Client-Server Model 2 Steps Process 2:00 
   HTTP Messages 2:23 
    HTTP Messages 2:24 
   HTTP Requests 3:09 
    HTTP Requests 3:10 
    Example: HTTP Request Header 3:17 
    Coding Example: HTTP Requests 4:29 
   HTTP Responses 7:15 
    HTTP Responses 7:16 
    Example: HTTP Response (Header & Body) 8:00 
   header() 11:47 
    header() Overview 11:48 
    Coding Example: header 14:02 
    Coding Example: header() Error 14:52 
   GET Method 18:55 
    GET Method 18:56 
    Coding Example: GET Method 20:13 
   POST Method 21:09 
    POST Method 21:10 
    Coding Example: Sample Form Using the POST Method 23:50 
   Accessing POST Data in PHP 26:38 
    Accessing POST Data in PHP 26:39 
    Coding Example: Accessing POST Data via $_POST 28:15 
   GET vs. POST 29:54 
    GET vs. POST 29:55 
   Example: Accessing POST Data via $_POST 31:20 
    Example: Accessing POST Data via $_POST 31:21 
   Homework Challenge 33:00 
    Homework Challenge 33:01 
  Web Application Development 14:11
   Intro 0:00 
   Version 2.0 Changelog 0:09 
    Updating the Site's Current Form to Use the POST Method 0:10 
    Creating Admin Website 2:55 
    Dynamically Generated Department List 12:40 
  Writing to Files 17:38
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Review of File I/O 0:40 
    Review of File I/O 0:41 
   fwrite() 1:38 
    fwrite() 1:39 
    fputs() 2:20 
     'r+' 2:31 
    Coding Example: fwrite() 2:59 
   fopen() Access Modes 8:41 
     'a' and 'a+' 8:42 
     'w' and 'w+' 11:34 
   Homework Challenge 14:47 
    Homework Challenge 14:48 
  Web Application Development 28:14
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   Updated Open File Functions 0:19 
    openItemsDataFile ( ), openDeptsDataFile ( ), and openLastAddedFile ( ) 0:20 
   insertItem() 6:25 
    insertItem() Overview 6:26 
    Functions: createItemDataString ( ) and updateLastItemAdded ( ) 7:07 
   addItemToDepartment () 16:03 
    addItemToDepartment () Overview 16:04 
    Functions: createDeptDataString ( ) and updateDepartment ( ) 17:55 
  HTTP POST: File Uploads 22:51
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   POST Data Encoding 1:13 
    POST Data Encoding 1:14 
    When Data is Included in the Body of the HTTP POST Request and is of the Content Type 1:31 
    When Uploading Files Using HTTP POST 3:17 
   Uploading Files 6:22 
    Uploading Files 6:23 
    If Encoding Type is Not Set to Multipart/Formdata 9:27 
   $_FILES Superglobal 10:59 
    $_FILES Superglobal 11:00 
   Structure of $_FILES 12:15 
    Structure of $_FILES: Name, Type, tmp_name, Error, and Size 12:16 
    Coding Example: $_FILES Superglobal 13:34 
   Moving an Uploaded File 15:39 
    Introduction to Moving an Uploaded File 15:40 
    move_uploaded_file ( ): Definition and Example 16:40 
   Homework Challenge 21:19 
    Homework Challenge 21:20 
  Web Application Development 15:30
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Uploading Item Image File 1:22 
    Uploading Item Image File 1:23 
   Uploading Item Image File (cont.) 2:43 
    Altering insertItem ( ) 2:44 
    Helpfer Functions: getFileExtension ( ) and moveUploadedFile ( ) 4:30 
    isValidItem ( ) 13:03 
  Introduction to Object-Oriented Programming 32:44
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Object-Oriented Programming 0:56 
    Introduction to Object-Oriented Programming 0:57 
   Associative Arrays 5:27 
    Associative Arrays 5:28 
   Classes 7:27 
    Classes Overview 7:28 
   Defining Classes 8:24 
    Defining Classes 8:25 
    Declaring Class Properties 9:25 
    Coding Example: Classes 10:11 
   Objects 12:18 
    Objects Overview 12:19 
   Classes vs. Objects 12:49 
    Classes vs. Objects 12:50 
   Instantiating Classes 14:58 
    Instantiating Classes 14:59 
    Coding Example: Instantiate an Item Object 16:30 
   Object Properties 19:21 
    Access and Set an Object's Property 19:22 
    Coding Example: Set & Access the Properties of an Item Object 24:23 
   Homework Challenge 30:22 
    Homework Challenge 30:23 
  Web Application Development 17:47
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Version 5.0 Overview 0:50 
    Version 5.0 Overview and Examples 0:51 
   Outputting Object Properties 12:38 
    Outputting Object Properties 12:39 
   Array Object Properties 14:18 
    Access and Set Array Value 14:19 
  Object Methods 39:57
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Object Methods 0:52 
    Definition of Object Methods 0:53 
   Calling Object Methods 3:25 
    Calling Object Methods 3:26 
    Coding Example: Simple Object Methods 4:44 
    Object Methods and Return Values 7:02 
   $this Variable 10:06 
    $this Variable: Definition and Example 10:07 
   $this Variable (cont.) 15:51 
    $this Variable (cont.) 15:52 
   Getters & Setters 21:21 
    Getters & Setters Methods 21:22 
   Object Methods In Strings 25:46 
    Object Methods In Strings 25:47 
    Coding Example: Outputting Method Return Values in Strings 27:41 
   Using $this to Call Other Methods 28:49 
    Using $this to Call Other Methods 28:50 
   Homework Challenge 34:18 
    Homework Challenge: 1-3 34:19 
   Homework Challenge (cont.) 36:20 
    Homework Challenge: 4-6 36:21 
   Homework Challenge (cont.) 37:52 
    Homework Challenge: 7-10 37:53 
  Web Application Development 17:30
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Version 6.0 Overview 0:40 
    Version 6.0 Changes & Examples 0:41 
   Item Methods 0:53 
    Item Class Definition: getImageFilename() 0:54 
    Coding Example: getImageFilename() 1:58 
   Department Methods 7:33 
    addItem(), removeItem(), and isItemInDept() Method 7:34 
    addItemtToDepartment() & buildDeptObject() Functions 11:46 
    A Default Value Needed to Be Set for $items 16:26 
  Object Constructors 22:20
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Object Constructors 0:32 
    Introduction to Object Constructors 0:33 
    Coding Example: Object Constructors 1:43 
   Defining Constructors 3:26 
    Defining Constructors 3:27 
    Coding Example: Constructors with No Arguments 4:24 
   Constructor Arguments 8:09 
    Constructor Arguments 8:10 
    Coding Example: Constructor Arguments 9:49 
   Important Notes 16:13 
    Important Notes 16:14 
   Homework Challenge 17:35 
    Homework Challenge: 1 - 4 17:36 
   Homework Challenge (cont.) 19:13 
    Homework Challenge: 5 - 9 19:14 
   Homework Challenge (cont.) 21:40 
    Homework Challenge: 10 and 11 21:41 
  Web Application Development 16:19
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   Version 7.0 Overview 0:39 
    Version 7.0 Overview 0:40 
   Item Constructor 2:19 
    Item Constructor 2:20 
   Department Constructor 7:47 
    Department Constructor 7:48 
   Customer Constructor 12:23 
    Customer Constructor 12:24 
  More Magic Methods 53:37
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   Magic Methods 1:12 
    Magic Methods 1:13 
   Destructors 2:45 
    Destructors Overview 2:46 
    Coding Example: Calling Destructors 4:30 
    Coding Example: Object Destructor 9:19 
   _to String () 16:12 
    _to String () Overview 16:13 
    Coding Example: _to String () Magic Method 18:10 
   Access Modifiers 21:23 
    Introduction to Access Modifiers 21:24 
    Access Modifiers: Public 21:39 
    Access Modifiers: Private 22:18 
    Access Modifiers: Protected 22:41 
    Object Properties and Methods 23:06 
    Coding Example: Public Access Modifiers 26:48 
    Coding Example: Private Access Modifiers 28:30 
   _get() 31:37 
    _get() Overview 31:38 
    Coding Example: _get () Magic Method 33:30 
   _set () 36:23 
    _set () & the Magic Method 36:24 
   Using Getters & Setters 44:37 
    Coding Example: Using Getters & Setters 44:38 
   Homework Challenge 50:33 
    Homework Challenge: 1 - 6 50:34 
   Homework Challenge (cont.) 51:41 
    Homework Challenge: 7 - 12 51:42 
  Web Application Development 31:12
   Intro 0:00 
   Version 8.0 Review 0:12 
    Version 8.0 Review 0:13 
   private Object Properties 1:15 
    private Object Properties 1:16 
    Coding Example 2:54 
   _toString() Methods 6:51 
    _toString() Methods 6:52 
    Coding Example 8:09 
   DataFile Class 13:27 
    DataFile Class & I/O Operations 13:28 
    Using DataFile Class: Instantiate a DataFile, DataFile open () Method, and DataFile close () Method 18:09 
   Homework Challenge 29:35 
    Homework Challenge 29:36 
  Classes vs. Objects 37:49
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Class vs. Object Review 0:58 
    Class vs. Object Review 0:59 
   Static Properties 2:42 
    Static Properties 2:43 
   Scope Resolution Operator (::) 5:26 
    Scope Resolution Operator (::) & Static Property 5:27 
    Coding Example: Accessing a Static Property Using the Scope Resolution Operator 7:57 
    Coding Example: Accessing a Static Property in a Class Definition 10:33 
    Coding Example: Using a Static Property as an Instance Counter 14:18 
   Static Methods 18:51 
    Static Methods Overview 18:52 
    Coding Example: Static Methods 21:39 
   Classes vs. Objects 26:28 
    Classes vs. Objects: Diagrams 26:29 
   Class Constants 30:24 
    Class Constants Definition 30:25 
    Coding Example: Using Class Constants 31:55 
   Homework Challenge 34:01 
    Homework Challenge: 1 - 5 34:02 
   Homework Challenge (cont.) 35:25 
    Homework Challenge: 6 - 10 35:26 
  Web Application Development 21:07
   Intro 0:00 
   Version 9.0 Overview 0:12 
    Version 9.0 Changes & Examples 0:13 
   Output Class 1:08 
    Output Class & Static Methods 1:09 
    outputHtmlSelector ( ) Method 2:43 
    outputItemSelector ( ) Method 4:53 
    outputDeptSelector ( ) Method 6:42 
   buildObject() Methods 11:54 
    buildObject() Methods & Examples 11:55 
  Exceptions 22:43
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   try Blocks 0:44 
    try Blocks Definition 0:45 
   catch Blocks 2:03 
    catch Blocks: Definition and Syntax 2:04 
    Coding Example: try/catch Blocks 3:48 
    When an Exception Object is Caught & Error Handling 5:59 
   Exception Class 7:02 
    Exception Class 7:03 
    Coding Example: Using try/catch to Catch an Exception Thrown from a Method 8:04 
   Re-Throwing Exceptions 16:39 
    Re-Throwing Exceptions 16:40 
    Coding Example: Re-throwing an Exception 17:21 
   Homework Challenge 20:40 
    Homework Challenge: 1 - 5 20:41 
   Homework Challenge (cont.) 22:17 
    Homework Challenge: 6 22:18 
  Web Application Development 22:00
   Intro 0:00 
   Version 10.0 Overview 0:11 
    Updating addItem.php, addItemToDept.php, and error.php 0:12 
    Updating DataFile Class: open ( ) Method & try/catch blocks 7:45 
   Version 10.1 Overview 13:37 
    Version 10.1 Changes & Examples 13:38 
    Updating DataFile Class: close ( ) Method & logWarning ( ) 20:17 
  Cookies 39:47
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   What is a Cookie? 1:15 
    Definition of Cookie 1:16 
   HTTP - A Stateless Protocol 2:17 
    HTTP - A Stateless Protocol 2:18 
    Purpose of Cookies 4:10 
   Set - Cookie Header 6:21 
    Introduction to Set - Cookie Header 6:22 
    Coding Example: Set - Cookie Header 7:38 
   Cookie Header 9:45 
    Introduction to Cookie Header 9:46 
    Example: Cookie Header 10:27 
   setcookie() 12:33 
    Introduction to setcookie() 12:34 
    Example: Using setcookie 13:54 
   Cookies Attributes 15:48 
    Cookies Attributes Overview 15:49 
    Common Cookies Attributes: Domain 16:24 
    Common Cookies Attributes: Path 17:04 
    Common Cookies Attributes: Expires 19:34 
    Coding Example: Setting Cookie Attributes 20:58 
   $_COOKIE Superglobal 27:03 
    $_COOKIE Superglobal 27:04 
    Coding Example: Accessing Cookies from PHP Using $_COOKIE 29:45 
   Security Implications 34:44 
    Security Implications 34:45 
   Homework Challenge 36:10 
    Homework Challenge: 1 - 4 36:11 
   Homework Challenge (cont.) 37:47 
    Homework Challenge: 5 - 7 37:48 
  Web Application Development 39:11
   Intro 0:00 
   Lesson Overview 0:17 
    Lesson Overview 0:18 
   instanceof Operator 1:34 
    instanceof Operator 1:35 
   Objects with Object Properties 2:53 
    Objects with Object Properties 2:54 
   Version 11.0 Overview 6:41 
    Version 11.0 Changes: Cart and CartItem Classes 6:42 
    Version 11.0 Coding Example 10:40 
   Version 11.1 Overview 31:03 
    Version 11.1 Changes & Examples 31:04 
  Introduction to Sessions 46:08
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   What is a Session? 0:53 
    What is a Session? 0:54 
   Client-Side Sessions 3:51 
    Client-Side Sessions 3:52 
   Server-Side Sessions 5:04 
    Server-Side Sessions 5:05 
   Session IDs 6:26 
    Session IDs 6:27 
    The SID is Used by the Server to: 7:08 
    A Client Passes an SID to the Server with Each HTTP Request Via: 8:15 
   Sessions in PHP 12:19 
    Sessions in PHP 12:20 
   session_start() 14:40 
    session_start() Overview 14:41 
    Coding Example: Using session_start () to Continue a Session 18:03 
   $_SESSION Superglobal 22:06 
    $_SESSION Superglobal Overview 22:07 
    Coding Example: Setting a Session Variable via $_SESSION 25:22 
   Accessing Session Data 28:08 
    Accessing Session Data 28:09 
   Deleting Session Data 31:43 
    Deleting Session Data 31:44 
    Coding Example: Deleting Session Data 32:16 
   Configuring PHP Sessions 36:14 
    session.cookie_lifetime, session.cookie_domain, and session.cookie_path 36:15 
    Coding Example: Configuring PHP Sessions 37:28 
   Configuring PHP Sessions (cont.) 40:56 
    session.use_cookies, session.use_trans_sid, and session.use_only_cookies 40:57 
    Coding Example: Configuring PHP Sessions 42:25 
   Homework Challenge 42:55 
    Homework Challenge: 1 - 5 42:56 
   Homework Challenge (cont.) 44:10 
    Homework Challenge: 6 - 10 44:11 
   Homework Challenge (cont.) 45:27 
    Homework Challenge: 11 - 13 45:28 
  Web Application Development 11:00
   Intro 0:00 
   Version 12.0 Overview 0:12 
    Version 12.0 Changes Part I: Updating 'viewCart.php' & 'checkout.php' 0:13 
    Version 12.0 Changes Part II 5:03 
  Destroying Sessions 29:59
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Destroying Sessions 1:02 
    Destroying Sessions 1:03 
   session_destroy() 2:10 
    session_destroy() Overview 2:11 
    Coding Example: Setting a Session Variable and Destroying a Session 3:18 
   Deleting Session Cookies 8:38 
    Deleting Session Cookies 8:39 
    Coding example: Deleting Session Cookies 9:17 
   Review of Steps 21:07 
    Review of Steps 21:08 
   Garbage Collection 21:50 
    Garbage Collection Overview 21:51 
    Coding Example: Garbage Collection 24:30 
   Homework Challenge 26:28 
    Homework Challenge: 1 - 4 26:29 
   Homework Challenge (cont.) 28:16 
    Homework Challenge: 5 - 9 28:17 
  Web Application Development 19:14
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   _autoload() 0:46 
    Introduction to _autoload () 0:47 
   Version 13.0 Overview 4:06 
    _autoload () and SessionManager Class 4:07 
    Updating 'viewCart.php' & 'checkout.php' 11:16 
  Introduction to Databases 21:24
   Intro 0:00 
   Lesson Overview 0:16 
    Lesson Overview 0:17 
   Flat Files 1:09 
    Flat Files: Definition and Example 1:10 
    Problems Associated with Using Flat Files as a Database 2:15 
   Relational Databases 3:29 
    Relational Databases 3:30 
    Relational Database Management System (RDBMS) 3:50 
   Tables 7:43 
    Tables 7:44 
   Columns 9:24 
    Columns 9:25 
   What is SQL? 10:45 
    Introduction to Structured Query Language 10:46 
    Standard Data Types of SQL 12:23 
   Primary Keys 13:19 
    Primary Keys 13:20 
   Primary Key Examples 16:36 
    Primary Key Examples 16:37 
  Introduction to MySQL 28:11
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   What is MySQL? 1:33 
    MySQL 1:34 
   MySQL Monitor 5:16 
    MySQL Monitor Overview 5:17 
    XAMPP & MySQL 5:58 
    In the MySQL Command: hostname, username and -p 7:05 
   Connecting to a MySQl Server 9:52 
    Connecting to a MySQl Server 9:53 
   Using MySQl Monitor 13:48 
    Using MySQl Monitor 13:49 
   GRANT Command 15:10 
    GRANT SQL Command 15:11 
    Privileges & Objects 18:18 
    Username, Hostname, and Password 19:37 
    Specifying Objects 20:05 
   Creating a PHP User Account 21:41 
    Creating a PHP User Account Overview 21:42 
    Meaning of all & *.* 23:35 
    Example: Creating a PHP User Account 23:48 
   Required Homework 26:27 
    Required Homework: 1 - 5 26:28 
   Required Homework (cont.) 27:28 
    Required Homework: 6 27:29 
  Creating Databases & Tables 23:01
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   Creating a Database 1:40 
    Introduction to Creating a Database 1:41 
    Example: Creating a Database 3:33 
   CREATE TABLE Command 6:43 
    CREATE TABLE Command 6:44 
   Data Types 7:39 
    Numeric Data Types: INT, INT UNSIGNED, and DECIMAL 7:40 
    String Data Types: CHAR (M), VARCHAR (M), and TEXT 9:23 
   Colum Attributes 11:00 
    PRIMARY KEY Attribute 11:01 
    AUTO INCREMENT Attribute 11:35 
   Items Table 13:07 
    Items Table 13:08 
   Useful Commands 17:04 
    SHOW TABLES Command & DESCRIBE Utility Statement 17:05 
    Example: Creating an Items Table 17:58 
   Required Homework 20:51 
    Required Homework: 1 - 6 20:52 
   Required Homework (cont.) 21:55 
    Required Homework: 7 - 9 21:56 
  SQL Command: INSERT 27:11
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   INSERT Command 1:20 
    SQL INSERT Command 1:21 
   Specifying Values 3:16 
    Columns with Numeric Data Types 3:17 
    Columns with String Data Types 3:34 
    Columns with AUTO INCREMENT 4:07 
   Inserting Items 5:21 
    Inserting Items 5:22 
    Example: Inserting Items 7:03 
   SQL Text Files 14:04 
    SQL Monitor Client 14:05 
    MySQL Monitor & the < Operator 15:15 
    Example 17:35 
   Required Homework 22:32 
    Required Homework: 1 - 6 22:33 
   Required Homework (cont.) 24:19 
    Required Homework: 7 - 10 24:20 
  SQL Command: SELECT 24:57
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   SELECT Command 0:42 
    SELECT Command: Definition and Syntax 0:43 
    Results of a SELECT Query 1:53 
    To Specify the Retrieval of All Columns from a Table 3:06 
    Example: SELECT Command 4:18 
   WHERE Clause 7:11 
    WHERE Clause 7:12 
    A SELECT Query with WHERE Clause has the Following Syntax 8:10 
    A Where Condition can Contain both Logical and Comparison Operators 9:44 
   Literal Values 13:24 
    Literal Values 13:25 
    Example: Literal Values 14:18 
   ORDER BY Clause 15:31 
    ORDER BY Clause & SELECT Query 15:32 
    Ascending and Descending Order 17:30 
    An ORDER BY Clause can Specify Multiple Columns to Order the Rows by 18:01 
    Example: SELECT Query with WHERE and ORDER BY Clause 20:32 
   Homework Challenge 21:59 
    Homework Challenge 22:00 
   Homework Challenge (cont.) 23:54 
    Homework Challenge 23:55 
  Using PHP from MySQL 32:43
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   PHP/MySQL Architecture 0:56 
    PHP/MySQL Architecture 0:57 
   MySQLi Extension 3:05 
    MySQLi Extension 3:06 
   Steps to Using MySQL from PHP 5:53 
    Four Steps to Using MySQL from PHP 5:54 
    Step # 3 7:18 
   Connecting to a Database 8:12 
    To Connect to a MySQL Database 8:13 
    To Test for Connection Errors 10:20 
   Running an SQL Statement 11:54 
    Running an SQL Statement 11:55 
    Example 13:30 
   Processing the Results 15:58 
    For non-SELECT Queries 15:59 
    MySQLi Object Property: affected_rows 16:19 
    For INSERT Statements on Tables with an AUTO_INCREMENT Column 18:07 
   Closing the Connection 19:45 
    Closing the Connection 19:46 
   Coding Example 21:24 
    Coding Example: Using MySQL from PHP 21:25 
   Homework Challenge 29:00 
    Homework Challenge: 1 - 4 29:01 
   Homework Challenge (cont.) 31:10 
    Homework Challenge: 5 - 9 31:11 
  Web Application Development 30:30
   Intro 0:00 
   Lesson Overview 0:14 
    Lesson Overview 0:15 
   sprintf() 1:28 
    sprintf() Overview 1:29 
    Example 1:56 
   INSERT Statements with sprintf() 5:15 
    INSERT Statements with sprintf() 5:16 
   Version 14.0 Overview 10:00 
    Version 14.0 Changes & Examples Part 1 10:01 
    Version 14.0 Changes & Examples Part 2 21:58 
  SELECT QUERIES from PHP 24:22
   Intro 0:00 
   Lesson Overview 0:14 
    Lesson Overview 0:15 
   SELECT Queries 1:21 
    SELECT Queries 1:22 
   MySQLi_Result Class 3:17 
    MySQLi_Result Class: num_rows 3:18 
    MySQLi_Result Class: fetch_assoc ( ) and fetch_object ( ) 3:59 
   fetch_assoc() 5:17 
    fetch_assoc() Overview 5:18 
    Coding Example: Using fetch_assoc() 9:00 
   stdClass Objects 12:46 
    stdClass Objects 12:47 
   fetch_object() 14:19 
    fetch_object() Overview 14:20 
    Coding Example: Using fetch_object() 16:45 
   Freeing Result Set Memory 18:42 
    Freeing Result Set Memory 18:43 
    Coding Example: Using free ( ) 20:01 
   Homework Challenge 22:07 
    Homework Challenge: 1 - 5 22:08 
  Web Application Development 17:06
   Intro 0:00 
   Version 15.0 Overview 0:13 
    Version 15.0 Changes & Examples Part 1 0:14 
    Version 15.0 Changes & Examples Part 2 8:43 
  Linking Tables 24:32
   Intro 0:00 
   Lesson Overview 0:16 
    Lesson Overview 0:17 
   A Departments Table 1:08 
    Departments Table 1:09 
    How Could We Model This in a Table: Option 1 1:26 
    How Could We Model This in a Table: Option 2 3:12 
   Database Normalization 4:37 
    Database Normalization 4:38 
   Foreign Keys 8:47 
    Foreign Keys 8:48 
   Linking Table 11:26 
    Linking Table 11:27 
   Multiple Column Primary Keys 15:30 
    Multiple Column Primary Keys 15:31 
    Example 18:51 
   Required Homework 22:34 
    Required Homework: 1 - 3 22:35 
   Required Homework (cont.) 24:10 
    Required Homework: 4 24:11 
  Web Application Development 24:00
   Intro 0:00 
   Version 16.0 Overview 0:11 
    Version 16.0 Changes 0:12 
    Version 16.0 Coding Examples 4:12 
   Version 16.0 (cont.) 18:30 
    Version 16.0 Changes & Examples Part 2 18:31 
  SQL Command: DELETE 10:33
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   DELETE Statement 0:30 
    DELETE Statement & Its WHERE Clause 0:31 
    Delete All Rows From a Table 2:57 
   Using DELETE from PHP 4:04 
    Using DELETE from PHP Overview 4:05 
    Coding Example: Using DELETE from PHP 6:37 
   Homework Challenge 8:53 
    Homework Challenge: 1 - 4 8:54 
  Web Application Development 16:02
   Intro 0:00 
   Version 17.0 Overview 0:11 
    Version 17.0 Changes 0:12 
    Version 17.0 Coding Example 2:51 
   Transactions 12:50 
    Database Transaction 12:51 
    Steps in Using Transactions 14:00 
  SQL Command: UPDATE 32:14
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   UPDATE Statement 0:54 
    UPDATE Statement & Its WHERE Clause 0:55 
    Example: UPDATE Statement 3:32 
   Using UPDATE from PHP 5:21 
    Using UPDATE from PHP Overview 5:22 
    Coding Example: Using UPDATE from PHP 6:53 
   htmlspecialchars() 9:04 
    htmlspecialchars() 9:05 
    Encoding Special Characters 9:23 
    Coding Example: htmlspecialchars() 13:41 
   addslashes() 20:40 
    addslashes() 20:41 
    Coding Example: addslashes() 22:52 
   Homework Challenge 27:55 
    Homework Challenge: 1 - 2 27:56 
   Homework Challenge (cont.) 30:14 
    Homework Challenge: 3 - 5 30:15 
   Homework Challenge (cont.) 30:41 
    Homework Challenge: 6 - 9 30:42 
  Web Application Development 12:33
   Intro 0:00 
   Version 18.0 Overview 0:12 
    Version 18.0 Changes 0:13 
    Version 18.0 Coding Example 1:24 
  SQL: Joins 42:16
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   DATETIME Data Type 1:52 
    DATETIME Data Type 1:53 
   Modeling Orders 5:12 
    Modeling Orders 5:13 
   Customers Table 10:46 
    Customers Table 10:47 
   Example 16:18 
    Example: Order Table in MySQL 16:19 
   Joins 22:26 
    Joins Overview 22:27 
    Inner Join 23:09 
    Example: Joins 24:11 
   Join Conditions 28:14 
    Join Conditions 28:15 
    Example 28:32 
    Join Queries 30:00 
    Example: Join Conditions in MySQL 30:36 
   Implicit Joins 34:42 
    Implicit Joins 34:43 
    Example: Implicit Joins 35:57 
   Aliases 37:28 
    Introduction to Aliases 37:29 
    Example: Aliases 38:55 
   Required Homework 40:32 
    Problem 1 40:33 
    Problem 2 41:01 
    Problem 3 41:17 
  Web Application Development 29:34
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Inserting Orders 0:44 
    Inserting Orders 0:45 
   Version 19.0 Overview 3:45 
    Version 19.0 Changes & Example Part 1 3:46 
    Version 19.0 Changes & Example Part 2 13:18 
   Version 19.1 Overview 21:10 
    Version 19.1 Changes 21:11 
    Version 19.1 Coding Example 22:18 
  User Authentication 26:13
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   User Authentication 1:31 
    User Authentication 1:32 
   Authentication with Sessions 2:34 
    Authentication with Sessions 2:35 
    Four Steps in Authentication via Sessions 2:50 
   Using Sessions to Restrict Access 3:58 
    Using Sessions to Restrict Access 3:59 
    Coding Example: Restricted Access Area 4:47 
   Authentication Methods 5:54 
    Authentication Methods Overview 5:55 
    Coding Example: Authentication Methods 7:31 
   Logging Out 9:57 
    Logging Out 9:58 
    Coding Example: Log Out 10:47 
   Users Table 13:50 
    Users Table 13:51 
    Example: Creating a Users Table 15:08 
   Password Hashing 17:30 
    Password Hashing 17:31 
    PHP and MySQL Built-in Hash Functions: sha1 ( ) and md5 ( ) 18:43 
    Coding Example: Password Hashing 19:27 
   Required Homework 24:41 
    Required Homework: 1 - 4 24:42 
  Web Application Development 14:36
   Intro 0:00 
   Version 20.0 Overview 0:13 
    Version 20.0 Changes & Examples Part 1 0:14 
    Version 20.0 Changes & Examples Part 2 5:05 
    Version 20.0 Changes & Examples Part 3 7:29 
   Version 20.0 (cont.) 8:31 
    Version 20.0 Changes & Examples Part 4 8:32 

Hello, and welcome to the first lecture in Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be providing an overview of all the topics covered in the course, as well as briefly discussing the prerequisites required.0006

This is, as the name implies (Advanced PHP with MySQL) an advanced PHP course that is aimed at 0016

prior PHP developers--developers that already have PHP experience.0022

And what it is aimed at is teaching those developers to be able to add database-driven functionality to their website.0026

We are going to be learning how to integrate a MySQL database into your web applications.0034

This course is specifically a direct continuation of the Introduction to PHP course that I have taught here at Educator.com.0039

And so, it is not a prerequisite that you have taken this course, but for those of you that have taken that course here,0048

you will be able to see how the material from there is going to continue directly in this course.0054

The content of this advanced course is going to break down into three different categories.0060

We are going to be covering advanced PHP concepts, which is going to be stuff like learning about how to perform file input and output.0064

We are going to be learning about how to use sessions, and then cookies, and so forth.0071

This course is also going to provide an introduction to object-oriented programming, so it assumes you have no prior knowledge of that.0077

We are going to learn about the basics of what object-oriented programming is and how to use it in PHP.0084

And we are going to provide an introduction to what databases are--specifically, the MySQL database.0089

And we are going to cover the basics of the most common SQL commands (which is a structured query language)0095

(which are commands that you use to interact with a database).0101

A main feature of this course is building up this mock web application that we call the Educator Store.0106

We are going to be continuing building upon the application that we developed in the introductory course.0113

And what we do--the way the course is going to proceed--is that I am going to introduce topics;0119

we are going to go over some lecture examples; we will have a homework assignment; 0124

and then, we are going to take the material that we have learned and integrate it into this web application, 0127

so we can see the material learned in a real-world example.0132

More or less, what is going to happen is: we will have one lesson on material and new topics, and then we'll have a lecture that follows that0137

that is integrating that material into this web application.0144

If we go ahead and take a look at our Educator Store website, this is the application that we are going to be developing.0149

It is a simple store with a number of different departments in it, where you have different items that you can choose,0159

that has information about the items that we are going to be able to pull from a database.0167

You will be able to add items to your cart; so, for example, we can add a basketball and a T-shirt.0171

You will be able to remove items from the cart.0180

You can check out; and what that will allow you to do is enter, for example, shipping information.0182

I'll just show you quickly what this looks like.0191

And what you will be able to do is go ahead and submit an order, and it will store the order in the database.0200

We are going to be developing, on the front end of the store, this Shopping Cart functionality that we have just looked at.0206

On the back side, we are going to be creating an administrator website called the Educator Admin site,0212

where we will be able to log in, and then perform administrative functions on the site.0217

For example, we will be able to add a new department to the store, if we wanted to, using this interface.0225

Let's create a department called Winter Clothes.0230

And then we can add items to our department, so we would be able to select the Winter Clothes department, and we want to add our winter jacket to it.0236

And then, add it to our department; and then, what we will be able to do is: this is going to be making changes directly in our MySQL database.0244

And then, now, when we go back to our homepage, we will be able to directly see that those changes on the admin site show up in the store.0250

So now, we have a Winter Clothes department; we can see that it has this winter jacket that was already in another department.0256

And we can add it to a cart and check out with it, just as before.0261

Additionally, there is a View Order section of this administrative website where you will be able to go0265

and view any orders that users have placed.0271

For example, we can look at the second order that was placed, that was of this value at this time; and this is the order that we have just placed.0274

And it shows the item number and the quantity and so forth.0279

And so, it is going to store information about those orders; and we are going to learn how to implement all this.0282

Initially, a lot of this is going to be done in a file database system.0285

We are going to learn about file input and output to implement the storage of this data (for example, information about the items in the departments) in files.0290

Then, we are going to migrate it, as the course progresses, over into a MySQL database,0299

and then just continue to add functionality to it, such as being able to update things, delete things...0303

for example, deleting departments, being able to view orders, and so forth.0308

And then, as part of our user authentication, we will be able to log out.0312

And so, we will learn how to implement a basic user authentication log in/log out system.0315

As mentioned, what we will be creating is a session-based shopping cart that is going to utilize cookies,0326

which is a term you may have heard about before; if not, we are going to learn about that in the course.0332

We are going to learn how to create a MySQL back end for this website that is going to allow us to store0336

all of the data about the store's items, about its departments, about orders placed...0341

And then, we are going to be developing that separate administrative interface to do things like we saw,0346

like adding new departments, deleting departments, being able to view orders, and so forth.0351

And we are going to learn how to implement a basic user authentication system for that0355

that is going to allow us, when a user logs in, to verify against a MySQL database 0359

if that username and password for a particular user are valid, for example.0364

As far as object-oriented programming goes, this course is going to provide an introduction to it.0371

So, we are going to assume no prior knowledge of object-oriented programming.0376

Some of the topics that we are going to talk about, as it relates to object-oriented programming, are classes and objects,0380

which are two terms you may have heard used before, and they are basic object-oriented functionality programming concepts.0386

We are going to be learning about those; we are going to be learning how to create your own user-defined classes.0391

And then, we are going to learn how you can use object-oriented functionality to improve your code, and to make it more flexible, for example.0399

So, we are going to learn about the benefits of why you also use object-oriented programming.0407

MySQL, as you likely know (if you chose to take this course), is called an RDBMS (Relational Database Management System).0413

And it is a system that is used to manage and store large amounts of data.0423

For example, maybe you have a store with 1,000 items in it, and you want to store all of the information about it.0427

Or you have 100 customers, and you want to store all of their addresses, and so forth.0431

You typically use a relational database to do that; and MySQL is a relational database with a system built on top of it0436

that allows you to manage that database and interact with it.0443

A main feature of this course is that, not only will we be learning about how to set up a MySQL database and how to interact with it0447

(using what is known as SQL, which is Structured Query Language), but we are also going to learn, 0453

as importantly, how to do that from PHP code.0457

There are two different topics we are going to be covering: we are going to be covering how to use the database/how to set up a database,0460

and then we are going to cover how to take what we know about databases and implement that0465

so that we can interact with it in our PHP code.0469

As far as interacting with databases, students are going to learn how to query a database (which is to request information from a database--0472

for example, say "give me all of the orders in the database that were placed in the last month").0480

You are also going to learn about inserting, updating, and deleting entries in the database.0486

And these directly correspond to SQL (Structured Query Language) commands, which you may have heard about before.0491

And then, when you query a database, it is known as a select command.0499

And so, we are going to learn about these four different commands and how to use them, first just using a database0503

as you would just in plain MySQL, and then also through PHP.0511

For example, one of the things that we are going to be doing is actually working at the Command Prompt.0515

There is a program we are going to learn about called MySQL Monitor, which allows you to connect to a MySQL database0520

and do things like run queries and run these SQL commands we were talking about.0526

For example, something you will learn about is a select query.0531

Let's say we want to pull up information about all of the items in our particular store.0538

We can run a query from this MySQL Monitor program--and this is something you are going to see run live in the code in the lectures.0544

And you will be able to see the results of that.0552

And so, what you are going to do is: you are going to learn about the commands, and then you are also going to get to see them in action.0553

This is our way of teaching MySQL and SQL and how to run commands and how to learn about MySQL databases.0559

And then, we are going to move it and shift it over to where we are going to be doing this sort of interaction,0566

not from a command line, but from a PHP program.0570

Just to cover a little more specifically the topics that we are going to examine in this course,0576

we are going to learn about file input and output; we are going to learn how to read from, and how to write to, files.0581

We are going to learn the details of the HTTP POST method, and specifically, we are going to learn how to upload files using HTTP POST method.0587

And what that is going to allow us to do is: on our administrative interface site, when we add a new item to the store,0595

as you saw in the store, all of our items have the images: we are going to learn how to upload an image for a new item, for example.0600

And we are going to learn about the details of the HTTP POST method in order to do that.0606

And if you don't know what that is, we will be learning about that in this course.0611

As mentioned, we are going to be covering the basics of object-oriented programming.0615

We are also going to talk a bunch about what cookies are and something known as state.0618

And we are going to talk about how we can use cookies and functionality built into PHP to implement sessions.0623

What that is going to allow us to do is implement our Shopping Cart.0629

And sessions...if you don't have experience with that, that is fine; we are going to be learning about that.0631

That is going to allow you to track one user interaction from another.0636

So, for example, when a user adds an item to a shopping cart, and then they view another item,0641

like when you go to amazon.com, for example--you can see, "OK, you have one item in your cart."0645

Well, you implement that functionality using sessions, and we are going to learn about that.0649

We are going to learn about how to set up a MySQL database and what a MySQL database is and how to interact with it on a basic level.0654

We are going to talk about the details of SQL, the Structured Query Language.0661

As mentioned, we are going to learn about the select command, and we are also going to learn about 0666

the insert, update, and delete commands, which are the foremost command commands that you will be using with MySQL.0670

And so, we are going to learn about how to use those in this MySQL Monitor client program.0676

And then, we are going to learn how to implement those in PHP (which, actually, is this next bullet point).0682

We are going to learn how to access a MySQL database from PHP.0686

And then, we are also going to learn how to implement a basic user authentication system,0690

where we are going to take what we have learned about using MySQL from PHP, and be able to query or request information from0694

our MySQL database, and say, "Does this user exist in the database with this username and password?"0702

And we are going to show how to implement restricting access to pages, based on whether that user exists or not.0707

You may have already figured out the course prerequisites from what we talked about in the slides.0714

You just need a solid understanding of the basics of the PHP language.0719

And what I am going to use as the defining characteristics of the prerequisites for the course are0725

is that you have an understanding of all the material covered in my Introduction to PHP course here at Educator.com.0732

So, the only knowledge that you will need to know about PHP is anything that has been covered in that course.0739

If it hasn't been covered in there, you don't need to know about it.0744

So, for those of you that have not taken that course, and have some PHP experience, you can go there and look at the lessons 0747

and see if you understand everything; and if not, take lessons and learn about the material that is going to be used in this course.0753

And also, you can use it as a way to review any material to prepare for this course.0759

It is also assumed that, for this course, students are going to have no prior experience with either object-oriented programming or working with databases.0766

And that is one of the main features of this course: that we are going to be, for databases, for example,0777

assuming you have never worked with a database before; so we are going to teach you the basics of0782

how to set it up, how to create it, how to interact with it, and then how to use it from PHP.0785

And then, object-oriented programming--we are going to introduce that as if you have no object-oriented programming background.0790

If you have background with either of these, that is great--it is going to help in understanding the material.0796

But definitely, this course was designed so that you don't need to have prior knowledge or experience with these two areas.0801

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.0810

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application.0005

In particular, we are going to be adding a new version called version 4.0.0011

And the main feature we are going to be adding is allowing...when we add an item to the store on our admin website,0014

we are going to allow the user to upload an item image file along with the form.0023

As you saw in our last example of the web application (our last web development lesson), if we look at our old admin site,0029

and we go to add an item to the store, it adds the item to the store.0038

However, when we go to view it, it doesn't actually have an image for it.0057

And these are the two items we added from the last time we did the web application lesson.0064

And so, we are going to fix that problem today; we are going to allow you to upload an image.0070

And we are going to make use of what we learned in our last lesson about file uploads using the HTTP POST method.0074

What we need to do is alter addItem.php, which is our admin form that allows us to add a new item to the store.0083

Specifically, we need to change the encoding type of that form.0091

It's a POST form; we need to change it to multipart/form-data, because as we learned in our last lesson,0096

when you are doing file uploads, you need to set the encoding type to that value.0101

We are going to add a file input tag, which we are going to be using to have that input element to upload an image file.0106

And then, what we are also going to do is remove the image file extension dropdown box, where we can pick GIF, JPEG, or PNG,0113

because what we are going to do is: now that we are uploading the file, we are going to write it into our code0120

so that it is going to be able to dynamically figure out what the extension of that image file is.0124

If we look at addItem.php, and we look at the new version of it down in our form, we can see that we have added0130

this enctype attribute and set it to multipart/form-data, and then we have also added a file input tag.0139

And we are setting the name of it equal to itemImage.0152

And we have gotten rid of that image file extension dropdown menu.0156

In order to upload an image for a new item to the file, what we are going to be doing is updating our insertItem function,0166

which, in our last lesson, we saw added a new file to our items.txt file, and also update the lastAdded.txt file.0174

But we are going to alter this, so that it is going to be able to handle the image file upload.0182

And we are going to do that by providing information to it that is provided from the FILES superglobal that PHP provides for us.0187

For example, if we look at our new addItem.php script, we can see, at the beginning here,0195

that we have added a new line for processing form variables that is going to test if a file input element was submitted0202

that was named itemImage, which was the name that we gave to our file input element on this form.0213

And if so, it is going to return the associative array associated with that file upload,0218

which, as we saw in our last lesson, contains things like the name, the temporary location of the file, how big it is, content type, and so forth.0224

And if not, we are going to set it equal to null--sort of the same thing we do for processing all of our form variables.0230

And then, what we are going to do is: if we look at our old data processing section of addItem.php, 0238

we can see that our insertItem function just took an associative array containing the information submitted on the form for that new item.0246

Well, in our new version, because we are uploading an image, insertItem is going to take that same new item information,0255

but it is also going to provide to insertItem a copy of the information provided in the FILES array.0262

And in order to use this updated insertItem function, we are going to be creating a couple of helper functions.0273

One is called getFileExtension, and what that is going to do is: we are going to use that to extract0281

the extension of the image file that was uploaded.0287

So, as before we had a dropdown box where we would select the extension of the image file;0290

now we are going to create this helper function in utilLIB.php that is going to, 0294

from the name of the file that was uploaded, be able to figure out what its extension is.0298

We are going to create a helper function called moveUploadedFile, which is going to take the process of moving 0302

the item's image that was temporarily uploaded to our tmp directory, and moving it into the item images directory in our web application.0310

And one thing to note, that we are going to go over, is: in the getFileExtension method, we are going to be using a new PHP function called pathinfo.0320

Let's take a look at our new insertItem method.0330

And as we can see, it takes two parameters now: it takes an associative array with information about the new item,0341

and then it also takes a copy of that information in the FILES superglobal for a particular image that was uploaded.0348

The beginning is basically the same: we are getting the new item ID for this particular item.0357

But then, what we are also going to do is supply to this getFileExtension function the value associated with the name key in the FILES superglobal.0365

So, for example, for our itemImage uploaded file, we are going to get the name of that, which is the name of that file0380

on the client machine where it was updated from; for example, if we are updating baseball.gif, then what we are going to be doing0389

is supplying to getFileExtension that name, baseball.gif; and then, we are going to be setting the associative array associated with our item;0398

we are going to set the image file extension key equal to that extension.0407

We take a look at getFileExtension: what it does is takes the file name that we are providing it, which is going to be 0413

something like baseball.gif, basketball.gif, whatever; and we are going to use this pathinfo function provided by PHP.0419

What pathinfo does is takes in a file, or a path to a file, and then returns an associative array of information about that particular file.0429

Specifically, it provides a couple of keys, like the dirname (the directory name of the file), the name of the file,0440

and what we are most interested in: the extension of the file.0448

What this is going to do is return an array of information about that particular file.0455

And then, we are going to test and see if an extension key exists in that array (which it will for an image file we have uploaded).0459

And if so, it is going to set our file extension equal to that.0469

And then, this is just some conditional text to return the file extension, if it existed.0472

So now, this first thing we have done is: we have set the file extension for our particular item, using this getFileExtension helper function.0482

The next thing we are going to do is move that uploaded image from the temporary directory into our application's image directory.0493

We are going to make use of this new function I created, called move_uploaded_image.0500

And what that does is: it is going to take two parameters.0505

The first one is going to be the absolute path to the temporarily uploaded file.0510

And, as we learned in our lesson on file uploads, that is contained under the tmp name key in our FILES array for our particular uploaded image.0516

And then, it also takes what we want to rename the file to.0529

And this move_uploaded_image is going to know the directory where to store the file, but we need to provide it the file name.0533

So, what we are going to do, as we have been doing for all of our items, is: the name of the item's image is just going to be the item's ID.0538

In this case, it is the new item ID, followed by the image file extension that was returned from getFileExtension.0545

If we go to our move_uploaded_image function, we can see that it takes two parameters:0555

the source path (which is the path to the temporary uploaded file), 0562

and then the destination name (which is the name we want to give to this item's image file).0567

Now, move_uploaded_file is the function provided by PHP that we talked about.0573

And what it does is takes two absolute paths: it takes the absolute path to the temporary file 0578

and the absolute path to the destination file where you are going to move the file to.0582

Instead of just providing the name of the file, we also have to provide the location of it.0591

And so here, we are creating a variable called destPath, which uses the SERVER root, along with our IMAGE_DIR constant0595

to set the path of the image directory, and then append to that the name that we provide for our item image.0606

This is going to be a path that is going to point to the image directory, 0618

and it is going to have the file name being 1007.jpg, for example, if an item 1007 was added.0622

Then, we just go ahead and call the move_uploaded_file; it will move it to the image directory and return true or false on whether that was successful or not.0631

After we have done that--we moved the uploaded image--the rest of this function is the same.0640

It goes ahead and updates our items.txt file with all the information about the new item.0646

For example, it is going to add a new row to this file.0653

It is going to update our lastAdded.txt file with the item number of the new item that we have added.0655

The difference is in the beginning, where it is going to extract the file extension of the file we uploaded, and then also move that file.0663

If we go and try out our new version of this admin site, version 4.0...let's create a new item and call it Basketball #2.0671

And then, we are going to browse to a basketball image; we actually already have an image...0688

Well, actually, let's do a baseball bat; and I am just pulling this image from our current images directory, because we already have that.0700

Let's call it Bat #2.0708

So now, when we click Add Item, it is going to add the item to our items.txt file--add all the information about it.0715

It is also going to move this baseball bat image into our items directory.0722

So, if we go to addItem, it is going to say the item was successfully added; it was assigned item 1007.0727

If we go and look at a version of the store, and we click on View Cart, all the way at the bottom,0733

we can see our new item, and now it actually has an image that we can click on--0738

whereas, in our previous version of the web app, we didn't have an item image.0741

So now, we have gone and are able to upload an image.0746

If we click on it, it goes to the item.php page, and it works just as well--it is able to pull that image out.0749

If we go and look at our images directory in version 4.0, we can see that we have created a file called item-1007.gif,0757

which is a copy of that baseball bat image that we uploaded.0766

We can see that it is appropriately named: it is item-1007, which is the ID of that new item.0770

And it has the appropriate extension, which is .gif, because the image that we uploaded was a GIF file.0775

And so, our code was able to extract that from the file.0779

One other small change we made to this version of the web app is: we also updated the isValidItem function,0785

which validates that data that is submitted on our addItem form.0794

And we updated it so that it would also check and make sure there were no errors in uploading the image file for our item.0799

If we go and look at (and this is in our utilLIB file) isValidItem, we can see that now it takes two parameters.0807

And if we go back and look at addItem.php, we can see that we pass isValidItem not only the information 0817

in the associative array about the new item, but also that item image data that is taken from the FILES superglobal.0830

And this is opposed to our last version, where we just passed it non-image information about the file.0836

In our new isValidItem, we take two parameters, the second one being information about the image data file.0847

We just have a test here to make sure that both of them are not null.0853

We have the same test for the non-image information that we provided.0856

We just test that the name, price, and description are all provided, that the name and description are strings, and that price is numeric.0861

We have also removed the test to make sure that the image file extension was a string,0868

because we are automatically pulling that on our own; it is not being supplied anymore.0875

If we go and look at our last version of this function, we can see that it tested to see that the image file extension was a string.0880

But we are not providing that on the form anymore, so we don't include that as part of our test.0890

And then, what we have done is added a test called imageTest that just tests 0894

that the error key that is set in the FILES superglobal for our uploaded image is equal to 0.0898

As we learned, 0 means that there was no error in uploading the file.0908

And then, assuming that all of these tests pass, our item is valid.0912

And so, that is the validation we have added for this addItem.php form.0919

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.0924

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

Today's lesson is a very exciting lesson, because we are going to be providing an introduction to object-oriented programming.0005

Specifically, we are going to talk a little bit about, just in general, what object-oriented programming is.0012

We are going to talk about how, in a way, we have been doing somewhat of a means of object-oriented programming through the use of associative arrays.0018

We are going to talk about what classes are and how to define them.0026

And then, we are going to talk about what objects are and the difference between classes and objects,0031

which is a common difficulty to understand for first-time students to object-oriented programming.0036

We are going to talk about what is known as instantiating classes, or creating objects.0043

And then, we are going to talk about how to get and set properties of an object we create.0048

Object-oriented programming is a paradigm of programming that allows you to work with objects in your code.0057

You take real-world objects, such as a person, and you model that in your code with user-defined data types.0068

And your programs work by manipulating and performing different functions on these different objects.0077

It is kind of an abstract concept, so it is maybe best explained by example.0085

As mentioned, for example, in the real world, there are people; and you have a person who has a first name and a last name.0090

Now, what we can do is take this real-world object, this person object, and model that in our code in a code object.0108

What we would do is create a user-defined data type that encapsulates information about that real-world object person.0117

So, we might create a class in our code that allows us to create what are known as person objects.0125

And a person object will have different attributes to it: you might have, for example, a first name attribute and a last name attribute.0135

What we do for object-oriented programming is take these real-world objects and model them in our code as a user-defined data type.0150

So, this person object is actually a user-defined data type that we are going to create, and that is known as creating a class.0158

Now, there are a number of benefits for using object-oriented programming, 0167

one of which is that it makes your code a little bit easier to understand and talk about.0171

It is more intuitive to humans to talk about dealing with different objects (for example, a person object),0174

and saying, "I want to perform this operation on a person," as opposed to talking about integers and arrays.0181

Additionally, it is a way to pass around a related amount of data in one particular variable.0188

For example, one of the things we are going to be creating in our web application is a cart object that is going to represent a shopping cart in our store.0195

So, what we can do is: maybe we will have a method that will say, "Calculate total."0209

And we can pass it a (this isn't the proper syntax, but) cart object.0221

What that is going to allow us to do is: within that cart object, it is going to contain all of the information 0229

about all of the items in the cart, what quantities they are, and so forth.0233

Now, this is as opposed to maybe (instead) having a calcTotal method where we have to provide 0237

the item ID of each particular item, and the price of each particular item, and so forth.0246

And now, we can pass all that information in a cart.0255

Another way would be if we had an example that wanted to print out the name of a person.0258

We could just pass it a person object, and it could use that to extract the first name and last name of the person,0261

as opposed to having to pass two separate parameters, first name and last name.0269

One other thing to note, also: an important feature of objects is that not only can they contain data, but they also can have methods on them.0274

So, we could have this cart object that contains information about all of the items in our cart,0286

and in this cart object, we can do something called create methods, where the cart object will have a method called calcTotal.0291

What it is: we get a cart object in our code; we define it; we populate it with items;0304

and then, what we do is run this method on the cart object by itself, and it will calculate the total for us.0310

So, that is another benefit of using objects: they contain data, and then they also have methods and functions that they can operate on themselves with.0317

In a way, we have kind of been using object-oriented programming a little bit through the use of associative arrays.0328

As mentioned, one of the benefits of using objects is that you can encapsulate a number of different pieces of data--0336

for example, about a person--in one variable; you can create a person data type,0341

and then create a variable that is of that person data type.0347

And you just pass around that one variable, and you can access all of the information 0350

(as we are going to see), such as the first name and the last name.0354

We have kind of been doing that with...for example, we have been using an array in our web application a lot called items.0357

And items has contained a number of keys (for example, itemID).0365

When we have a function that needs to operate on an item, we are just passing it this variable items.0371

So, in a way, we have already been doing that data encapsulation.0377

Now, what object-oriented programming does is gives us a formal way to declare what properties are part of an item.0380

For example, in our store items, we have a couple of different properties that we are using.0388

We have an item ID, a name, a price, a description, and an image file extension.0393

And the way we having been doing that is modeling that as an associative array, with a key for each of these 0400

different properties of an item, and then setting a value to it.0405

But an associative array is just a general array that anybody can use.0409

You could add other key values to it; for example, you could just call something and assign a random key to it.0416

But what we are going to do is create a user-defined data type for an item.0425

We are going to create an item class, and that is going to allow us to create item objects.0429

And we will explain the difference between classes and objects in a little bit.0433

And what that is going to allow us to do is restrict what properties and what values a particular item object can have.0437

As mentioned, a class is a formal description of a particular real-world object that you are going to model in code.0449

It is essentially a template for a user-defined data type.0457

So, for a person, for example, we talked about the person object.0460

The person class would be a user-defined data type (it is something we can define in our code)0464

that says a person is an object that maybe contains two properties: it contains a first name and a last name.0470

And as mentioned, a class definition...when you create a user-defined data type, you can create properties in that class, such as first name and last name.0477

And then, as mentioned, you can also create methods, which we are not going to get into in today's lesson.0487

We are going to get into it in a future lesson.0492

That allows you to define methods that work on that particular object.0494

For example, for a cart object, you could say "calculate the total."0499

In PHP, the way you define a user-defined data type, which is called a class (and classes are used to create objects):0506

you use the class keyword; and class names in PHP follow the same rules as variable names, minus the dollar sign.0514

And by convention, they always have their first letter capitalized.0522

Additionally, the convention is: every time you define a new user-defined data type, you define it in its own file.0526

So, it follows a one-class-per-file convention.0533

And the PHP file that the class is defined in typically has the same name as the name of the class.0537

For example, if we are defining a Person class, we define it in its own file, and we are going to show what that looks like in a second.0546

And we are going to define it in a file called Person.php.0554

Typically, you also store your classes in, for example, a 'classes' subdirectory of your web application,0557

so that they all are located in one spot.0563

And then, what you can do is: when you define a class, you can define different properties.0566

For example, a person might have two different properties: it might have a first name and a last name.0570

Well, what you can do in a class is define properties using the syntax here of the public (which is a keyword),0575

followed by the variable name of the property you want to assign.0582

So, for any random object, we might have a property called property1.0585

We don't need to worry so much about the public keyword right now; we are going to talk a little bit more about that in future lessons.0591

But for now, we can just say that that is what we are going to be using to define our classes.0597

And when you define a property of a class, you can also provide it a default value.0601

For example, we could provide it a constant value, like the string literal value 1.0606

Let's take a look at a class we have created that is going to model an item in our store.0612

Here, we have a file called Item.php, because it is defining a class called Item.0617

We can see the class keyword here; we can see the name of the class immediately following the class keyword.0621

In this case, it's Item, and the first letter is capitalized.0627

And then, we can see that the class definition is located within a pair of curly braces.0630

What we have done here is defined a number of properties, which are also sometimes called attributes, or members, of a particular class.0636

We are saying that the Item class has five different properties.0644

One of them is going to be called itemID; and here is a comment for a programmer that is going to say that is going to represent the ID of the item.0648

It is going to have a property called name, a property called price, a property called description, and a property called imageFileExt.0656

These, again, over here, are just comments that describe to the programmer what these different properties are going to represent.0665

Here, what we have done is created our own user-defined data type.0672

We are saying, "We are creating a data type that is going to be called an Item, just as you would have an int or a float or a bool."0679

"Now, we have a new data type called item, and it is going to contain a number of different properties,"0687

"just as an array is a composite data type that can contain a number of different values in it."0693

And as we saw, we have been using associative arrays to hold a number of different data values for a particular item,0697

Now, we are saying we have this item data type, and it is going to contain a number of different pieces of data--0704

In this case, five particular pieces of data.0709

Now, this is valid PHP code; and you actually could go and load it in your browser.0712

If I go and load Item.php, it is not going to do anything, but it is PHP code, and it is what is called a class definition file.0716

And it tells PHP, when you create an instance of an Item class, what it is going to look like.0726

Objects refer to a particular instance of a class or a user-defined data type.0740

What an object is: it takes that class template (maybe that class template for Item you have created), and it fills in those values.0748

When you create an object, it is known as instantiating, or creating an instance of a class.0756

Let's take a look at a diagram that explains this a little bit better, that talks about classes versus objects.0769

Here we have a class; and this would be defined in our file, like in a class definition file, with the class keyword.0776

For example, let's say we define a class that is going to represent a person.0782

We are going to say that the person is going to have two properties, a first name and a last name.0788

Well, that Person class just defines what that data type will look like.0792

It is going to say that it is a data type that has two values: a first name and a last name.0796

Well, in our code, when we want to create a Person (it is called instantiating an object, 0801

when we want to use a Person object), we have to create an instance of it.0810

And then, what it does is: we are assigning that data type to a variable and assigning values to it.0814

For example, when we create an instance of a class, we create what is known as an object.0823

And now, an object is going to be a PHP variable (here, for example, we are going to call it person1).0829

And an object is going to have the values of the class it is representing populated.0835

So, maybe we are going to create a Person object called person1 with the first name Joe and the last name Smith.0841

And maybe we will create another instance in our code of a Person object.0848

It is called person2, and we are going to assign the name Jane Jones to that object.0854

In a way, it is very similar to in PHP, where there is the int (or integer) data type that defines what an integer is.0859

PHP knows what it is, and so that is sort of like the class for an integer.0868

But any time you want to use an integer in your code, you create a variable, and you assign it a value.0872

In an analogous way, what this statement here is doing is: this is creating an object called int1 that is of the Integer class.0882

So, it is kind of something similar to what we have been doing, except we are using our own user-defined data types.0891

In PHP, the way that you instantiate a new class, or you create an object of a particular class, is using the new keyword.0900

And it has this form here.0907

So, what we do is: we declare a variable, and using an assignment operator, we have the new keyword,0909

followed by the name of the class we want to create an instance of, followed by opening and closing parentheses.0916

So, this line right here says, "Create the variable person1, and then set it to be an object of the Person class."0922

So, "Have it be of the data type that is represented by the Person class."0931

Now, one thing to note is that, if you were to run this within your script, PHP has to know what a Person class is.0938

It is not something that is defined in PHP.0948

For example, in our last example, we defined our Item object in a file called Item.php.0952

So, Person is going to be defined (by convention) in a file called Person.php, and it is going to provide that class definition for what a Person is.0957

Well, PHP needs to know about that in order for this statement to make sense.0967

Any time you use a particular class in a file, you need to either include this Person.php file, 0970

or you can include the class definition with the script itself, which is not a recommended practice.0977

So, what we are always going to do is create our classes in separate files, and then include those within whatever scripts need them.0983

If we go and look at a script we call createItemObject.php, what this is going to do is instantiate (or create an instance of) our Item class.0992

Now, we defined our Item class as being a user-defined data type that has these five different properties to it.1002

Well, in createItemObject, the first thing we have done is: we have an include statement that says we are going to include this Item.php class definition file.1008

And here, we have sorted it in a subdirectory called classes, which is a common convention.1019

So now, our PHP has included Item.php, and it has that class definition for Item; it knows what Item is, so it can create an Item object.1024

Down here, what we do is create an instance of that class; we create an actual Item object.1034

We take the class, and we turn it into an object.1039

We are creating a variable called item1, and we are saying, "We are going to create this variable item1,1043

and it is going to be of the class type Item; so it is going to have the user-defined data type known as item."1048

Now, this right here doesn't do too much; but we are going to talk about properties in a second (which is going to show a little more).1055

This is code that just runs; it is not going to output anything.1061

But what it goes and does is loads that Item.php file, and then item1 is now an instance of that Item class.1065

We went and (it is not going to do anything, but) loaded it in our browser; we can see that it outputs this HTML header that we had in the file.1075

But it doesn't really do anything; but it shows that the code was appropriately run.1085

Now, as mentioned, you have to have the class definition file included within a script, where you are creating an instance of that class.1090

For example, here we are creating an instance of the class Item; we had to include the class definition file for item.php.1101

If not, PHP doesn't know how to declare it.1107

Let's say we misspell this, and we include a file called item3.php.1109

Well, now when PHP gets down here and tries to create an Item class, it is not going to know what it is,1114

because it hasn't included the appropriate file, Item.php.1120

For example, now, if we save this, and we go and run the script again, we can see a couple of things.1125

One is that we get a warning that says item3.php could not be found.1132

But the one we are more interested in for this particular lesson is: it says, "Class Item is not found."1137

It is saying, on line 20 (if we look back at our code), "You tried to create an instance of the Item class, but we don't know what the Item class is."1142

And so, that is where this error message comes in here: "Class Item not found."1156

One of the things that objects have, that we mentioned that classes have, is: they define properties that a particular object of that class can have.1163

For example, a Person object, or a Person class, might have two properties: a first name and a last name.1171

Well, in PHP, there is a special syntax that is used: it is a dash followed by a greater than sign1180

that allows you to set, and then also get, the values of a particular object's properties.1186

So, after you have already created an object--after you have done something like item1=new,1192

which is the keyword used to create a new instance of an item object, 1202

if we wanted to set a particular property of this item, we use this notation here.1208

So, what we do is: we have the name of the object variable that we created using the new method.1217

We have this dash followed by a greater than sign, and then the property that we want to set followed by the value.1225

For example, we know, in our Item class, we have a name property.1232

So, if we wanted to set the name of our Item object that we created, we say item1 (which is the variable1236

that refers to the new item object that we have created--so it's an actual object); 1244

we use this operator--the dash followed by the greater than sign, followed by the name of the property we want to set.1248

If we look back at our Item.php, it has a property called name.1257

And then, we are going to set it equal to maybe the string Basketball.1267

So now, what we have done is set the name property that is associated with this item1 object.1273

Now, one thing to note is that a class defines the data type of a user-defined data type; it defines what values it can have.1284

However, when we create a new object, it creates a whole new instance of that class.1294

For example, if we went down here, and we defined a new Item called item2, and we set it equal to an Item object,1301

this item2 has its own copy of the name property, so we can go down here and set the name of the item2 Item to Other--to something else.1317

Now, we have two objects that are of the Item class type (the Item data type).1336

And each one of those objects has their own copy of the properties defined.1344

This is how we represent different items in our code.1350

This is going to be item #1, that has the name Basketball; this is going to be item #2 that has the name Other.1352

And then, what we can do is (let me erase some of this here): we can also use that same - sign, 1360

followed by the greater than sign, to access a particular object's property.1367

For example, we might want to echo this name property.1373

And the way you would do that would be: you get the object name, item1; then you have this dash sign, 1377

followed by the greater than sign, and then the name of the property you want to get the value of.1386

In this example here, this is saying, "For the item1 object, go and retrieve the value associated with the name property for that item."1395

Now, in our other example that I just erased...1406

In this case, what it is going to do is echo 'Basketball.'1410

Now, if we had run this same code on that Item we had just created (let's assume it was still here, up in this section);1414

if we had done, instead, item2, dash, greater than, name, what would be output would be 'Other.'1420

And that is because each Item object that we create has its own set of all of those properties defined in the Item class.1431

So, every time that we instantiate class Item using the new keyword, we create a variable, and we assign it this Item class type,1439

it gets its own version of all of these different properties.1448

Each one has its own itemID, its own name, its own price.1453

And the way you access and set those is using the dash, followed by the greater than sign.1456

Let's take a look at accessing and setting properties in action.1464

We have a script called itemObjectProperties.php that has the same beginning as our last script.1469

We include the Item class definition; we instantiate--we create a new Item object, and we set it equal to this variable item1.1476

And then, now we are going to go through and set all of the different properties of this Item, using this dash, greater than operator.1488

We are going to say, for item1 (which is this new Item object we have created), we are going to set its itemID to 1001.1494

We are going to set its name equal to Baseball, its price to $4.99, its description to this, and its extension equal to that.1501

And then, what we are going to do is access these different properties.1508

Now that we have set them, we can extract the values from that particular Item object.1512

So, on that Item object, we are going to extract all of the values into separate variables.1517

We are going to say, "Set a variable called itemID equal to the item ID that the Item object associated with the variable item1 has."1523

The key thing here is that it's the itemID associated with the item1 instance of an object.1535

In our last example, if this had been item2, the item ID could be the same, but typically it would be something different.1540

The key here is that, when you are accessing a property of a particular object,1548

you are accessing the properties of a particular instance of that object.1553

In this case, we are accessing the item1 instance of the object.1557

We go ahead and extract all of the different properties, using this dash, greater than sign.1561

And then, we just go ahead and output that.1569

If we go ahead and look at this code in our browser, itemObjectProperties.php,1572

we can see that what it has done is gone and, after having set all those properties, output all of the different values that we had set.1577

Now, one thing to notice is that...let's say we tried this code before we set any of the properties--1586

before we performed this set operation up here; well, our Item class, when it is initially created, doesn't have any values for these.1594

So, when this is run, when you try to access itemID, it is not going to return anything, because no value for that exists.1603

It, in fact, is null; so if we go ahead and save that script and reload it, 1611

we can see that, the first time we try to access the information associated with the item1 object 1616

(which is an object of the Item class), no values are set.1622

Now, as mentioned in our class definition, we can include default values.1627

So, let's say, for example, that we set a default value for the name property of an Item class.1631

And we will just call it default; so any time we create a new object that is of the class Item, it is going to have five different properties.1643

And the property name is going to have the value set to default.1654

And then, any other properties--you have to have manually set them, in order to have them set a value.1660

Now, you can overwrite this default property, which is what you would do, using that dash, greater than operator.1664

But at least, when this object starts, it has a default property.1672

So now, we go back and look at our code here.1674

After we have created this new Item object, and we try to retrieve all of its different properties,1678

this one for name is going to return that name 'default,' because it is already set when you create this Item class.1686

Before you set any properties to it, it already has a default value provided.1697

So, when we output this information before we have set all of the other values, it is going to output that name.1700

If we go and look at our code now, we can see that up here, it output the name 'default.'1706

And that is because we had provided a default value for it.1711

And so, you can see, also, that we were able (down here) to rename the object item1 to Baseball,1717

so that when we output the information for this object a second time, we can see that default has been changed to Baseball.1725

One of the key things to note is the difference between classes and objects; 1737

and that is a very complex concept when you are first starting to work with object-oriented programming.1741

Just to reiterate, a class is the template for a user-defined data type that you are creating.1749

You are saying, "I am creating an item class, and it is going to have 5 different properties," for example.1756

Now, any time you want to create a variable that is of that class, you instantiate it using the new keyword.1762

You are creating a new variable that contains all 5 of those properties--for example, for the Item object.1769

And every time you call this new Item object, it creates a whole new copy of all of those properties.1779

So, when we call item2--if we set this to item2=new Item(), item2, again, is going to have its own copy of all of those different properties.1787

So, the class just describes the structure of what an Item object looks like.1798

When you create an instance of the class using the new keyword, it creates spots in memory for all the different properties of that.1804

And you can set them; and each object you create has its own copy of those,1813

and you can set and change them as you need, during the course of your script.1817

For the homework challenge for today, I just want you to create a class called Address that represents a street address.1824

It should have four properties: street, city, state, and zipcode (which represent the different parts of this real-world object).1830

For example, you could have an abstract model of an address, and you could say, 1841

"We are going to model this address in our code as something that has these four parts to it."1845

Then, you do that in its own class definition file, and then, in a separate script, create an instance of the Address class using the new keyword.1850

And then, set values for all four of the properties of that object, using the dash, greater than syntax.1861

Then, like we did in the example, use the same dash, greater than syntax 1873

to access the values that you have set for those particular properties and output them.1878

So, you can see that you were able to define the class appropriately,1884

that you were able to know how to set the properties of the class, 1890

and also that you were able to access those properties of the class.1893

Be sure, when you do this, that you follow the one-class-per-file convention,1896

which means that you are going to define Address in its own file, called Address.php.1901

And remember that, in your script, when you create an instance of the Address object,1905

that you include that class definition file within your script.1913

That way, PHP knows what an Address class data type is.1917

And then also, just make sure (and we will get to this in future lessons) that when you define your properties1924

in your class definition file, you precede them with the public keyword.1930

And again, if we look at our Item.php, within the curly braces of this class's definition,1935

you have the public keyword, followed by a variable name 1943

for a particular property you want that object to have, followed by a semicolon.1948

So, here we have five different statements that declare properties for that particular class.1952

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1959

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application, incorporating what we have learned about objects so far.0005

Today's lesson is going to cover version 5.0 of the web application.0013

And as said, it is going to cover inserting objects into our web application, changing it 0017

from an application that modeled items and departments, for example, 0022

as associative arrays into one that models them as actual PHP objects.0026

We are going to have a quick lesson on how to output object properties within double-quoted strings.0032

And then, we are also going to talk about accessing object properties that are arrays,0039

and how to use the square bracket syntax to access values in those arrays.0043

So again, what we are doing is taking these items and departments objects that we have in our application;0052

before, they weren't official PHP objects, but we modeled them as an associative array.0058

For example, we would pass around to different functions an item associative array 0064

that contained a number of different keys (for example, name that would represent the name of a particular item).0070

What that allowed us to do was to pass around all of the information about a particular item in one variable--in this case, item.0077

Well, now what we are going to do is officially create that Item data type, that Department data type, by creating Item and Department objects.0084

So now, first of all, instead of passing associative arrays between functions to access item information,0095

we are going to be passing Item and Department objects in between functions,0100

and we are going to be accessing the Item and Department objects, rather than arrays.0105

What that is going to do is change how we access our item properties 0108

from the square bracket syntax (like is used here) to the object property accessor syntax,0112

which is the dash followed by the greater than sign, which we learned about in the last lesson.0119

For example, if we have an Item object that had been instantiated using the object accessor syntax, 0123

now this is how we are going to access the property name, or how we are going to refer to it to set its value.0133

Let's go ahead and take a look at what our Item and Department classes look like.0142

Here you can see, in our documentation that is generated by PHP Documentor, that there is a new section on the left-hand side here called Classes.0149

And what it does is provides documentation about the different classes in our web application.0158

You can see the Department and Item classes; you also see the Customer class, 0161

which we are going to talk about in a second, which is another class we have defined for this web application.0165

If we look at the Item class, and we look at the source code for it, we can see that we defined this class called Item with a capital I; that is the convention.0172

And if you look at the structure of our web application, the name of the file that this class definition is defined in is called Item.php, with a capital I.0181

It is in our Classes directory, which is in our Includes directory.0190

And again, this follows the one-class-definition-per-file convention, where we only have one class definition in each file.0193

And we can see that we have defined five different properties for an Item class.0201

It has a string property that is the itemID; it has string properties for the name, the description, and the image file extension.0208

And then, it has a float property for the price.0215

And you can see here, we have defined it using the public keyword, as we had talked about in our last lesson.0219

And so, that represents an Item object now.0224

So now, instead of using the associative array to access all these properties, we are going to access them as an object.0228

If we look at our Department class, we can see that it has three properties: deptID and name are two of them (both of which are string properties).0236

We can also see that it has the items property, which is actually an array.0246

It is an indexed array, if you will remember, of all of the item ID's that represent all of the items in a particular department.0250

What this shows is that the properties of a class can be of any PHP data type.0258

Here, we have strings, an array, an Item class; we have strings and floats.0263

And you can even have properties that are objects themselves, which we will see in some later lessons,0268

where properties defined in a particular class will be data types that are other objects, or other class types.0274

And so, what we have done is: now that we have created all of these different classes, or this Item and Department class:0284

we have to go through our web application and update all of the functions that used the associative array syntax0290

for accessing our Item and Department information, as well as any of the pages that accessed that information using associative arrays.0298

And it has been done in a number of different spots; there are a lot of spots on our application that have done that and been updated.0305

And we are not going to be able to go through all of them in the lesson.0311

But all of the changes are noted in the change log for version 5.0.0314

But I am just going to go through and talk about a couple of different changes that were made.0318

For example, if we look at our file library, we can see that now we have a new function called buildDeptObject.0324

Whereas before, when we read a line from departments.txt, and we used the explode function on it 0333

to extract all the information about a particular department, we used a function 0341

(if we look at our last version's documentation) called createDeptDataArray, and what it would do 0345

is create this associative array that represents the department; 0351

well, now instead of creating a departments array, we are going to create a Department object.0356

So, we have gotten rid of that createDeptDataArray function.0360

We also got rid of the createItemDataArray function, and we replaced them with buildDeptObject and buildItemObject, respectively.0365

And, as you can see--for example, in the buildDeptObject, we still take in an array that contains information in a line in departments.txt.0375

And now, instead of creating an empty array for our department variable, we defined a new Department object using the new keyword.0383

And then, we used the accessor syntax to go ahead and set its department and name values.0393

And then also, down here, we use it to set its items property to the array of all the different items' ID's.0399

And so, this is what we are going to use now to build our Department objects from our departments.txt file.0407

Likewise, the buildItemObject works in the same way; it is just that it defines a new instance of an item object.0415

And then, what it does is sets all the different properties; it just has more properties that it sets.0424

For example, now our createDeptDataString function has been updated.0432

Whereas before we passed in an associative array of department information, now we are passing it...0437

If we look at the documentation for it, we can see that the parameter that it takes 0442

is still called department, but it is actually a Department object--0447

whereas in our previous version, we could see that department was an array0450

(and as it says here, it is an associative array defining information on all of the information in our department).0459

One thing to note is that, for example, in our createItemDataString, this is our new version--version 5.0.0471

And we can see that what it does is: this one takes an object now.0485

So now, we are moving on to the string; this takes an Item object and creates an item string that we are going to store in our items.txt file.0490

Similarly, createDeptDataString now takes a department object.0497

And what it will do is create a string to store in our department data file.0502

As you can see, it uses this syntax to access different properties of the department, as well as the different properties of a particular item.0506

We have just gone through and updated all of the different methods.0517

For example, getDepartment now returns a Department object, as opposed to an associative array.0520

You can see, in the documentation for this, that it returns a Department object.0525

getDepartments returns an indexed array containing a Department object for each department in our store.0531

For example, if you look at the documentation, it says that it returns an array.0542

And the array is of Department objects, whereas before it was an array of associative arrays describing those different departments.0547

That is another thing to note: that arrays can contain any data type, including...0555

we know that they can contain other arrays, integers, booleans, all the scalar data types...0560

But they actually can also hold objects, as well.0566

So, in this case, we are returning an array of Department objects.0568

This is the pattern for the rest of these functions, as they have all been updated to use the Department and Item objects.0574

Additionally, if we look at (for example) Item.php, we can see that this is one of our pages.0586

Now, when we call getItem at the beginning of Item.php, it is going to return an Item object.0595

And so, you can see that now, when (for example) we set the title of our Item.php page,0602

we are using an object accessor syntax, whereas if we look (for example) at an older version of our web application,0609

and look at Item.php, you can see that we use the associative array syntax.0616

We have updated all of the functions to use objects and their objects' accessor syntax, as well as all of our different pages that previously accessed associative arrays.0622

One other thing to note is that we also created a Customer class, which is used with the checkout.php form.0638

If we look at our old version of checkout.php, we can see that we had this custDataArray that we used0645

to represent all of the information submitted on the checkout form, when the user submits their shipping address, and so forth.0658

For example, it has the street address, their first name, their last name, and so forth.0667

And it was an associative array, and we used it in a couple of different functions.0671

For example, in our emailOrder function, we would pass it this custData associative array,0675

and emailOrder would be able to extract information about that.0682

Well, now we have updated our emailOrder function: instead of using this custData array, what it is going to do:0685

if we look at version 5.0, we can see that what we have done is: 0695

now, when we call the emailOrder function, we are passing it a Customer object.0708

And you can see up here that we create the Customer object within this data processing section.0712

So, we declare a new instance of the Customer class, and then we set its different values.0717

And if we go and look at the code for our Customer class, we can see that it just 0724

has all the same properties that our custData associative array used to have.0734

It has (they are all strings) properties for first name, last name, street, apartment, city, state, and ZIP code.0737

So now, we have encompassed all of the information about a customer's shipping information into a Customer object that we can pass around.0744

Any functions that used that custData associative array before now use the Customer function.0752

One topic that I wanted to talk about was how to output object properties within double-quoted strings.0759

We know that you can output arrays within double-quoted strings (for example, an associative array).0766

This is supposed to be a curly brace.0773

We can output using this curly brace syntax.0779

Well, we can also do the same thing for object properties.0784

For example, let's say we have an echo statement, and we want to output, as a string, the name of this Item #1 object.0787

Well, the way you do that is: you use the accessor syntax on the item1 to get the property you want,0795

and you just simply enclose it in curly braces.0801

For example, if we go look at item.php, and we look down at...there is a call down in the output section0805

that outputs the item's image, and one of the things that you have to pass to the outputImg function0814

is the name of the image file that you want to output.0819

Well, the way we build that up is from the item ID, followed by a period, followed by the image file extension of that particular item.0824

Well, here, you can see: we have created a string, and using the curly brace syntax, 0830

we were able to include the item ID and the image file extension of this particular item that this page represents.0837

So, currItem is an instance of the Item object.0843

And by enclosing them in curly braces, we can output that within double-quoted strings.0847

That is a nice feature of being able to output object properties within strings.0853

Another thing that we had mentioned earlier is that object properties can be arrays themselves.0860

For example, in our Department object (let's look at the source code for it), we have this items property, which is an indexed array.0865

What we can do is: if we want to access values in that particular array that is a property of that object, there is a particular syntax that we use.0881

For example, what you do is: you use the accessor syntax to access that particular array property.0892

For example, if we had dept1 (which is a Department object), the way we would get access to that items array0904

or the items property would be to use this accessor syntax.0910

And then, what you can do is directly append to the end of it square bracket syntax, just as we did with any other array to access different values of it.0913

For example, to access the first item in the items property of this dept1 object, 0921

you just append the square bracket syntax right after you access the particular property.0929

Essentially, it is the same as if we had gone and created a temporary variable, and said $a=$dept1-->items, and then accessed it as $a[0].0941

We can do that directly in one statement, by just directly appending the square bracket syntax.0959

It also works for associative arrays, too, so this could be a string key.0964

And you can do this to set values, as well.0969

In this case, we were getting the first element of this items array of the dept1 object.0971

In this case, we are setting the first element of the items array of the dept1 object, just using an assignment operation.0977

And if we look at our addItemToDept function that has been updated to use objects,0986

we can see that addItemToDept is what we have been using to add an item ID to the items array of a particular department.0995

So here, the way that we do that is: we access that items property, which is an array.1006

We use the accessor syntax; and then, we just append our square bracket syntax to it.1012

And square brackets, as we know, with arrays--if you don't put anything in between them, 1017

and you use them in an assignment statement, it just says to add another element to that array.1022

So, this is saying, "Get this items array; append another element to it; and have it have the value itemID."1026

Now, this is opposed to if we look at addItemToDept in our last version.1034

We can see that we used a multidimensional array syntax, because our department object was represented as an associative array.1038

That is an example of how you can directly (in one statement, as opposed to two up here) access values in an array in an object.1050

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1062

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be expanding our knowledge of object-oriented programming by learning about object methods.0005

Specifically, we are going to talk about what object methods are and what their purposes are.0014

We are going to talk about the subject of how to call object methods--the syntax that is used to do that.0019

We are going to talk about a special variable, known as the this variable, which is going to be important for use within our object methods.0025

We are going to briefly talk about what are known as getter and setter methods.0033

And then, we are going to finish up by talking about how to output the results of object methods within double-quoted strings,0037

and how to use this this variable we are going to learn about to be able to call one object method from within another object method.0044

Classes can define functions.0055

In a way, we have been having our own function libraries.0058

For example, fileLIB.php has been a library that just contains a number of function definitions that we have been able to use.0060

Well, when you define a class (for example, the Item class), you can define functions.0067

And functions that are part of a class definition are known as methods.0075

And they are functions that work on a particular object.0081

So, when you define an instance of the Item class (for example), it might have a method that says returnCost.0087

And when you call that method on that particular item, it will return maybe the price property of that particular item.0095

The object methods are defined...and it is still a function, but again, the terminology with objects is to call them methods...0104

they are defined within the class definition, just like a class's properties.0112

And it is defined within the curly braces; we are going to take a look at what it looks like in a second.0116

It has the same syntax that we use for defining functions, in that it even uses the function keyword.0122

The one difference is that, at least for the time being, we are going to be placing the public keyword in front of the function keyword.0127

Let's take a look at a class Person where we have defined a class method.0137

For example, we have a Person class with two properties, firstName and lastName,0146

which would just be strings to represent the first name and last name of the person.0152

And this is what we have seen before; we have come across this when we first learned about objects, about how to define properties.0155

But also, if you look down here, you can see that we have defined a function.0161

It is within the curly braces of the class definition, which means that it is a method of this Person class.0165

And we use the keyword public, and then function; we say public function, 0171

and then we define the method just as we would any other function that we have done before.0176

In this case, we define a method called hello that takes 0 arguments; it doesn't return anything; it just outputs an echo statement.0181

All the rules that apply to functions that we had learned about in the introductory course,0193

that you know about from your experience with PHP, are going to apply to object methods, as well.0198

We know that we can define methods and objects; but how do we call them?0206

Well, first of all, you have to have an instance of an object to call the method.0210

And then, in order to call the method, you use the same accessor syntax that we use to access the values of the different properties.0214

And you use that to call an object's method.0222

For example, let's say we define a variable called person1, and we set it equal to a new instance of this Person class that we have talked about.0226

Well, in order to call the hello method on that Person, we list the name of the variable, followed by the dash and the greater than sign.0238

And then, instead of following that by the property name, we follow it by the name of the function.0247

In this case, we had a function called hello.0251

And the way that you distinguish it as a function, as opposed to a property, is: you include a pair of parentheses afterwards, 0253

which is sort of intuitive, because that is the syntax we use for functions.0262

Now, for example, if our hello method of our Person class took a parameter, then we would also specify the parameters0266

within the parentheses, just as you would any time we have been calling any other functions that take parameters.0277

Let's take a look at our Person class; we defined this function hello--let's take a look 0285

at a file called hello.php that is going to call that method, so we can see this in action.0291

We have a test file here that includes the definition of the Person class.0297

We instantiate, or create a new instance of, a Person object.0302

We go ahead and use the accessor syntax to set the firstName and lastName properties of this particular Person object, this instance of a Person object.0307

And then, we are going to call, or invoke, the hello method for this particular Person object.0317

In this case, we use the dash, greater than sign, and then we say hello with parentheses.0324

If we just quickly look back, all our hello function does is outputs or echoes a statement that says 'hello.'0330

If we go and look at this lecture example, and we look at hello.php, we can see that the output of it is A person says 'Hello!'0338

And that is a result of calling this method on this Person object.0347

And so, that is the syntax that you use to invoke an object's method.0354

One other thing to do is (for example): we could, just as with other functions, include parameters.0362

So, let's include one parameter--it's a string called world.0368

Now, we could go to our Person class, modify the function definition so that it accepts a string, and then say,0375

"We are going to do the same thing; we are going to have an echo statement, but we are going to echo the string that was passed in."0386

So now, we have an object method that can take a parameter, as well.0398

So, if we go ahead and (both of these are saved) reload our page (and let's make this string that we are passing in...0403

OK, it is world, so it will be different), we can say, "A person says 'world.'0409

So there, you can see how an object method works just like a regular function does.0416

One other thing to note is that object methods can return values, just like a normal function can.0424

For example, let's say that we had an object that modeled a shopping cart (which is something we are actually going to be adding to our web application).0429

Let's say we already have that, and we have declared an instance of it.0435

So, we have this cart1 variable that is an object of our ShoppingCart class.0438

Maybe that ShoppingCart class has a method on it called calcCartTotal, which is a function we have been using in our utility library.0443

Well, if you run that calcCartTotal function on a particular cart object, let's say it calculates that cart total and returns it as a value.0453

So here, what you do in order to get the return value of the object method is: you call it just like you would a regular function.0459

And you can use an assignment statement; so in this case, we are assigning the value returned from the calcCartTotal function into the total variable.0469

And that is the same thing as if we had maybe, instead, done total= calcCartTotal, or maybe we passed it an array of the items in the cart.0481

Whereas this would return the value--the return value of this function takes its place, and total gets set to it;0503

the same thing happens here--the return value of this whole object statement gets returned and gets set into the value total.0509

For example, we could alter our hello method of our Person class, 0520

so that instead of echoing the string, we could have it return a particular string.0531

For example, get rid of the echo statement and just have it return a static string that says, "A person says 'Hello!'"0536

So now, what we can do is: if we run this the way it is, what is going to happen is:0549

it is going to call this hello method; it is going to return a value; but we are not echoing it, and it is not echoing it in the function.0554

So, if we run this script again, nothing is going to happen; no output is going to happen for that function.0563

So, what we do is: we update it to just echo the result of that.0568

Here is an example of having an instance of an object, calling a method on it that returns a value,0574

and then using that value--using that return value, just as you would a return value from any other function.0582

Here, we are going to echo the value returned by this hello method of the Person object, which is going to be that string.0587

And if we refresh the page now, we can see that it goes ahead and outputs it.0595

That is an example of how object methods can also return values, as well.0600

Now, that particular function didn't do too much; it especially didn't do anything related to the object.0608

It just output a simple string: you could just create a regular function to do that.0615

Typically, the reason you create object methods is so that they can perform some actions on that particular object.0618

One of the main things that they can do is that the functions defined within an object can access the members, 0625

or the properties, of that particular object--and actually even the other methods of a particular object.0632

And the way that you do that is: there is a special variable called this: it's $this, and you can use it within class methods.0637

And what it does is refers to a current instance of an object.0646

And it is kind of an abstract concept, so let's take a look at what it looks like in code, so that it will make a little more sense.0650

Let's say we have our Person object, and we have our hello function.0659

Now, we have created a new method; you can have as many methods for a class as you want.0662

We are calling it getFirstName, and we just want it to return the first name of this Person object.0668

Now, we could access that using our typical accessor syntax; but for the sake of this lesson, and learning the material, we are going to do it through the method.0675

And what you do is: in order to access the firstName property of this particular Person object,0685

you use the this variable, and then you use the accessor syntax, followed by the property name that you want to get.0695

For example, if in our test script this.php, we define two Person objects.0703

We set both the firstName and lastName of each of the different objects.0715

And then, we are going to call this getFirstName method that we have defined on each person.0720

For example, person1 is defined...we set the firstName equal to Joe, and lastName equal to Smith.0726

When we call this getFirstName function, what it is going to do is invoke this getFirstName function.0733

And it is going to return the value of the property firstName of the this variable.0740

Now, the this variable changes for each particular object instance; so each object instance...0749

every time you call this getFirstName function, this is reassigned a new value.0755

So, when we call this function on our person1 object, this is going to refer to person1.0760

In a way, it is as if we replace it with person1/Person.0768

But the way you do that within a class definition is: you just use $this.0775

Now, the reason for doing that is that now we can reuse that.0779

If I go back and type it again...if we had person1 here, now this function would only work with a variable named person1.0783

By using this special variable $this that can change its value, depending on which instance of an object was being used,0789

we can reuse this method, and so it is going to work for every object we create of this type.0797

For example, person1--we had set their firstName equal to Joe, so when we call getFirstName on person1,0807

this in that method is going to refer to person1, and it is going to get its firstName property, which is Joe.0814

Now, when we go down here on person2, and we call getFirstName, that this variable, when that method gets run,0821

is going to refer to this person2 object, whose first name is Jane, and it is going to return that property.0827

And so, what that does is: it is the same method that gets run, and has the same code, but it returns different values,0836

because each time that method is called, that this variable gets reset to the variable of the object that you are working on.0842

For example, when we run this script, what it is going to output is the name of both of our different people.0855

So, if we run this.php, we can see that the Person firstNames are Joe and Jane.0865

If we look at our code, we can see that we just had two echo statements 0869

that called the getFirstName method on person1 and getFirstName on person2.0876

So, you can see that each of those methods returned a different value.0880

It returned the firstName value for that particular instance of that object, because 0885

when the method is called, that this variable changes to become the instance of the object you are operating on.0890

Now, one thing to notice is that, for example (and this is a required thing):0898

let's say, in this function, we wanted to access this firstName property.0902

Well, you might think that you could just access it using this $firstName, because you would say, "Hey, we have this class;0906

it has the firstName variable defined in it; let's just return firstName."0913

If we go ahead and try and do this, and we run our script, we are going to get an error saying that that variable, firstName, is undefined.0920

So, it is very important that when you want to access the properties of a class within a method, you use the $this keyword.0929

So now, when we set it back to what it was before, it is going to work.0943

So again, because this $this variable is kind of an abstract concept, I want to draw a little diagram to explain it a little bit better.0952

For example, let's say we have a class that we have defined called X.0960

It has one property in it, and we'll just call it var1.0966

And it has one method that is just going to return the value of the var1 class property.0976

And it is going to use the this special variable.0995

What this essentially does is: when we define a class, we are defining a template.1012

We are saying, "This is a template for any variables that we declare of this data type (of this class, or this user-defined data type)."1015

So, we are saying that any time we define a variable that is of the class X, 1024

it is going to have a property var1, and it is going to be able to execute this var1 function.1029

And so, it is code that defines a data type and defines methods that can be run on that particular data type.1035

And then, it can be used in multiple spots.1043

So, just as in our other application, we are going to define two instances of this X class and set var1 equal to 'A'...and 'B'...1045

Now, again, what is going to happen is: as this class is a template, when you create this new instance of the class X1080

and assign it to variable 1, this is saying that variable x1 is going to have this template assigned up here.1091

So, it is going to have a var1 variable; so when we assign var1 to it, it gets its own copy of that var1 variable.1098

So, each instance of a class (and this is an important concept, which is why I'm harping on it a little bit--it's that)...1104

every time you create a new instance of a class, you are creating a whole copy of this class here, in a new way, for that particular variable.1113

So, we are creating a whole copy of the var1 property, and we can set it to value A.1122

Now, when we create this x2 variable that is another instance of that class X, 1128

we are creating another whole copy of that class, which includes its own version of var1.1134

Oops, I made a mistake down here.1139

When we set x2 var1 equal to B, x2's var1 property is completely separate from x1's var1 property; it is its own instance.1142

In the same way, for example, if we were to call this getVar1 method on our x1 object, it is calling its own version of that particular method.1153

And the way it does that is using this $this keyword.1172

As mentioned before, what happens when you call this getVar1 method is: this function up here gets replaced with...1175

I'll just use a shortened syntax without the public keyword...1185

So again, it is as if, when x1 calls this object method, it calls that method on itself--on its own instance.1210

So, what it does is: when this method gets run, this gets replaced, essentially, with x1.1218

It is just as if we were accessing that var1 property of x1 directly.1224

Now, when x2 calls this getVar function, this is going to get replaced with x2.1229

What this is reinforcing is this concept that the class provides a template of the properties and methods that a particular class can have.1238

And when you instantiate, or create a new instance of, each class, 1249

you get copies of each of the different properties, and a new var1 property for each instance.1254

And you also get your own version of the getVar function.1261

And the way that you do that is using this $this method, which PHP is able to dynamically interpret when you call that function.1264

So now, we can define this getVar1 function one time, and it is going to work on any time we have an object of the class X.1272

One common operation performed on objects, a common method that is performed, is to get and set their property values.1284

We just saw an example, in our Person object, of something that is known as a getter.1289

It returned the value of our firstName property; it was called getFirstName.1294

So, getter methods retrieve the value of an object's property, and its setter methods set the value of an object property.1298

Now, we have been able to do this: let's say we had our person1 from before--we can set its firstName using this syntax here.1307

So, we actually don't need these getter and setter methods.1317

But it is a common thing that is done, and it is a special topic within object-oriented programming, 1324

and within PHP, that we are going to get to in another lesson.1330

So, I just wanted to at least mention it--at least introduce the concept of it.1333

Now, we can set the firstName property of this person1 using this syntax that we use, the object accessor syntax.1339

But instead, we could create a setter method and say person1 (let's say we set firstName equal to Joe)...1350

we could define a method called setFirstName that passes it the value Joe.1365

And what that is going to do is: if this is a setter, it is going to take this value Joe,1374

and then, within the class definition, it is going to set the value of the firstName property by using the this variable.1379

We are going to see that in a second.1387

And one of the main reasons I am demonstrating this is that it shows how you can use the this variable1389

to not only return values from an object, and to access property values of an object, but also to be able to set them.1394

For example, if we look at a new version of our Person class, we have the same two properties: a firstName and lastName.1402

And then, we have defined what are known as getter functions for each of the properties.1411

We defined getFirstName and getLastName, and what they do is use the this special variable 1415

to return the first name and last name, respectively, of this particular instance of a Person object.1420

And we also have setter functions, which take a parameter.1429

Again, object methods can take parameters, just as any other function does.1431

And then, here, we are using the this variable, and we are using the accessor syntax, to set the value of a particular property.1435

In this case, when this function is called on an object, we are saying, "On that instance of that object, 1444

we are going to have the firstName property, and we are going to 1451

set it equal to this firstName variable, which is passed in here."1453

This is how you can use the this function in order to also set object properties.1456

If we go and look at a test script, gettersSetters, we can see that we create a new Person object.1467

And now, instead of using the method that we had done before to set the first name and last name of the Person1473

(which uses this accessor syntax), we are going to use our setter methods.1481

We are saying person1: set firstName Joe; set lastName Smith; the same thing down here...1485

And it is going to perform the exact same function as when we had set them manually.1491

And when we go to output the person's first and last name, we are going to use the getters getFirstName and getLastName on each object.1494

What they are going to do is show that those values we set with the setter methods actually set those methods for those particular objects.1502

When we load this script up, we can see that it says Person #1's first name is Joe; 1509

Person #1's last name is Smith; and the same for Jane Jones, who is Person #2.1520

And so, what you can see is that we have been able to set object properties within an object method (and that uses the this function).1527

And then, we are also able to access those properties, using the this variable.1536

And we do that using our getter methods, down here.1540

One thing I want to talk about now is: object methods are functions, and they return values.1548

And before, we have had strings where we have the value of a function that we want to output.1554

And you can't include that within double-quoted strings--you can't call a function within double-quoted strings.1562

However, you can include the output of object methods within double-quoted strings.1567

And the way you do that is using the curly brace syntax.1573

So, let's say we define a variable person1; we are going to define it as a new instance of the Person class.1576

We are going to use that setter we defined--we are going to set its firstName to Joe.1583

And then, we want to output the first name.1586

Well, what we can do is: if we want to output the value that getFirstName method on person1 object returns,1589

we simply call the method, using our normal method-calling syntax, and just enclose it within curly braces within our double quotes.1596

And this is opposed to having to use the concatenation operator (and I'll abbreviate).1604

It is a nice little trick that makes our code easier to work with: now, we can use methods within our string.1626

And that is something that...let's say this wasn't an object; normally, for a function, we couldn't do that anyway.1638

So, if we had a function called getFirstName (not an object method, just a function), 1644

we wouldn't be able to include that, normally, within double-quoted strings anyway.1655

Let's take a look at this in action: we have our same Person object that we had in our last example.1662

It has the getters and setters for the first and last name.1668

We go ahead and instantiate two Person objects and set them with the same names we did before, Joe Smith and Jane Jones.1672

And now, what we are going to do is: whereas before we output their names using this concatenation operator1680

(we said Person, First Name, the dot operator, and then we called the method getFirstName),1685

now we know we can do it all within one string.1692

And so, instead of (actually, let's move it back again) having three separate strings here that we are concatenating together,1695

we can include it all in one; and you do that using this curly brace syntax.1701

This does the same thing as the last script does, except we are making use of including the outputs of an object method within a double-quoted string.1707

If we look at what it looks like when we browse to it, it is going to look exactly the same; and you can see that here.1717

One final topic that I want to talk about is using the $this variable...you can also use that to call other methods from within object methods.1730

For example, when we were in our (let's take a look at our Person class) getLastName,1742

we could use $this to refer to the particular instance of the object...1751

Well, when this method runs, this gets set to whatever instance of that object you are running the method on.1756

And we use this to access that lastName property of that Person object.1763

We can also use $this to call object methods from within itself.1770

For example, we have our function hello down here; before, if we look at the very first version of it, it just returned a string.1776

Well, now what we are doing is calling our function hello; and within our function hello, we are going to say, "Joe says hi" or "Jane says hi."1791

And the way we are going to do that is by making use of this getter function we defined for this Person class.1800

And we are going to call it within this object method.1806

And the way we do that is using this variable again.1808

When we create a variable, a Person variable, and we set its first and last name, and then we call the hello method (for example)1812

on person1, what is going to happen is: hello is going to get called; $this is going to get replaced with the person1 object.1823

And then, it is going to say, "Call the getFirstName method on it."1831

Well, getFirstName is defined within the class; it will go up here, and it will say, "return $this-->firstName."1835

So then, $this will also know that it refers to Person object 1, because PHP does that for you automatically.1840

It is going to get the firstName property of it and then return it.1848

So then, it is going to put that name here, and then concatenate it to this "so-and-so says hello."1851

This is an example of how you can use the this variable to also call object methods from within other object methods.1857

You can access object properties using the this variable, and you can also call other object methods within them, as well.1866

If we run this script, we can see that now we get an output message that says "Joe says hello" or "Jane says hello."1873

When this ran, and this function is called, we are calling on this object the getFirstName method.1886

So, on person1, we are calling getFirstName; when we go to getFirstName, 1894

we are returning the firstName property of the person1 object that is replaced by this.1899

And then, that is how that gets output.1905

Now, this isn't a particularly real-world example; something that is a little more real-world is maybe...1907

because we are typically not going to be using getter and setter functions, as you will see in a future lesson...1914

something that we might do is: maybe we will define a function called getFullName.1919

Because fullName is not a property of a Person object, you can't access it using the accessor syntax.1923

For example, let's just say this was in a random script: you couldn't say fullName, because fullName is not a property of person1.1932

What we can do, though, is create a useful method that is going to return the full name.1946

And what that is going to do is concatenate the first name and the last name, which are properties of that object, and return that.1949

And that might be a useful function: we are going to say, "Give me the full name of this person."1955

If we define an object method in our Person class called getFullName, it will return a string.1960

And this is using our curly brace syntax, again, to output...well, in this case, it is outputting object properties within a string.1966

We are saying, "When you call getFullName, you are going to return a string that is going to contain1973

the value of the firstName property of this particular object, followed by a space, followed by the lastName property of this object."1981

And so now, in our function hello, we can make use of this function.1990

You can make use of it externally, but we are going to make use of it internally here,1996

to again reinforce the idea that you can call object methods within other object methods.1999

We are going to update our hello function to now call $this-->getFullName.2004

So, when hello gets called, it is going to say, "On this object, call the getFullName method."2009

And then, it is going to return a string that has the first name and last name (concatenated together) of this particular object.2016

And then, we are going to concatenate that 'says hello,' and so hello is going to 2025

return a string that is going to say 'Joe Smith says hello' or 'Jane Jones says hello.'2031

If we look at the output of this script, we can see 'Joe Smith says hello'; 'Jane Jones says hello.'2036

That is just a combination of all the different things that we have learned, 2045

and something that is maybe a more practical use of how you would see these object methods used.2048

For today's homework challenge, it is kind of an advanced homework challenge.2060

I'm going to have you create a class called HttpRequest that is going to represent an HTTP GET request message.2063

And that is something we learned about in an earlier lesson in the course.2071

I want this HttpRequest class to have two properties: one called uri, which is a string 2076

(and that is going to represent the particular URI that this particular requested object would be requesting), 2082

and then a headers property, which is an associative array that is going to contain 2088

name/value pairs of any HTTP headers for any particular HTTP request this HttpRequest object would be representing.2094

And then, now that we have our properties, I want you to add a method to the class called addHeader.2102

It takes two parameters (in this case, they are called name and value),2108

where the name represents the name of a particular HTTP header, and the value represents the value of the header.2113

So, for example, the name might be host (which is an HTTP header), and the value might be educator.com.2119

What this addHeader method is going to need to do is: it is going to need 2130

to be able to access this headers property of the HttpRequest object in order to add this name/value pair to it.2134

And so, in order to do that--to access, from within an object method, the properties of that object--we need to use the this variable.2142

So, you are going to have to use the this variable within this method here.2149

Then, I want you to add a method called getHeaders; and what it is going to do is return a string in proper HTTP request format2153

that represents all of the headers that are in this headers array up here.2163

So again, you are going to have to use the this variable to access this headers array.2166

And what you are going to do is loop over the array, and then output each header on its own line, with the name and value separated by a semicolon.2170

And so, that is going to be a method that is going to be used internally within the function.2178

Finally, I want you to define a method called getRequest.2182

And this is the method that is going to be used by people that are using this class.2186

They are going to instantiate an HttpRequest object; they are going to set its URI; they are going to maybe add some headers using the addHeaders function.2190

And then, they are going to call the getRequest method, which is going to say, 2198

"Give me the formatted HTTP request that is represented by the URI and headers of this particular object."2201

What getRequest is going to do is create the required first line of an HTTP request,2210

which has the method name (in this case, it is going to be get) of the URI and the HTTP version.2219

And then, it is going to call the getHeaders method to append all of the HTTP headers to this first line that it creates.2224

This is an example of an object method calling another object method.2233

In this case, getRequest is going to be calling the object method getHeaders.2237

Then, just in a separate script, I want you to instantiate an HttpRequest object.2242

Set the uri property to index.html (and you can just use the object accessor syntax).2248

And then, add (using the addHeader method) two HTTP headers: one called Host, and one called User-Agent (which are both real HTTP headers).2255

You can set them to whatever value you want--it is not as important for the example,2264

but just the fact that you are going to be practicing using object methods.2269

And then, call the getRequest method on that object and output what it returns between pre tags,2274

which is going to show the output formatted in this form down here, which is like a computer text format.2281

And then, verify that your output has the form shown here.2290

For example, this first line of yours should be exactly the same as this: it should say GET /index.html HTTP/1.1.2293

And then, it should have two header lines, one for Host and one for User-Agent.2302

And their values should be set to whatever values you supply to that addHeaders method.2305

Notice that they are formatted properly with a colon and a space in between here.2310

And you are going to be doing that in your getHeaders method.2315

And so, for this, you need to make sure that you are appropriately using the this variable2321

to call, for example, the getHeaders method from within the getRequest method, 2327

and also to be able to access that headers variable and the uri variable.2333

For example, when we are outputting this first line in our getRequest method, we are going to have to have access to the uri property of this class.2337

So, as a little hint, one of the things that you are going to need to do is use the $this-->uri in order to access that.2346

So, just make sure that you properly use the this variable, and that, when calling the methods,2355

you also practice using that same accessor syntax that we used to call methods.2361

For example, let's say we had an object of HttpRequest called http; to call the getRequest method on it,2366

as you will remember, we use this dash, greater than sign, the name of the method, followed by parentheses.2382

In this case, getRequest doesn't take any parameters, so it will just be empty parentheses.2387

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.2393

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application, incorporating what we learned in our last lesson about object methods.0005

We are going to provide an overview of the new version of the web application, which is going to be version 6.0.0013

We are going to provide an overview of the changes.0018

And the changes for this version of the application are that we have added some methods 0020

to our Item and Department classes that improve the functionality of our code.0026

And then, we are going to specifically talk about the methods we have added to the Item class, and then the methods we have added to the Department class.0032

As mentioned, we have just added methods to both our Item and Department0042

that are going to allow us to learn what we used in the last lesson, and also to improve the functionality of the application.0047

For our Item methods, we have added one method to the Item class called getImageFilename.0056

And what it is: it is like a helper function...because we know that an Item's image's file name is the ID of the Item,0063

followed by a period, followed by the property image file extension, every time we have been, for example,0074

trying to get the name of an Item's image, we have had to concatenate those two together: 0082

the ID and the image file extension, with a period in between.0085

Well, now we can create this helper function that is going to put that functionality in one function.0089

So, any time we want the file name of an image, we just call that particular function.0095

It is kind of like in our last lesson, when we talked about the getFullName method that was able to get the full name of a Person object0099

by combining the firstName and the lastName and putting it into one method, so that every time you want to get0107

the full name of a Person, you don't have to access two separate properties; you can just call one method.0112

So, if we take a look at getImageFilename, if we look at our Item (oops, that was our last version) class,0121

we can see that here is a definition of our Item class.0135

But now, we have an object method defined down here.0137

In this case, it is called getImageFilename, and what you can see that it does is: it simply returns a string0142

that is the concatenation of the item ID of this particular instance of the object, concatenated with the value of imageFileExt.0147

For example, it might be 1001, followed by a period, followed by jpg.0156

Here, you can see, as we learned in our last lesson, that we use the special variable $this 0162

to access the properties of a particular instance of the Item class from within the object's methods.0168

So now, any time we want the image file name, we can just call this method; and we can see that this is going to be useful in two separate places.0179

For example, in our Item.php page, when we output the image of our Item, or we call the outputImg function,0187

and we manually extracted the itemID property of this current Item that this Item.php page is showing the information for,0198

it added the dot and then went ahead and added the image file extension.0211

So, we are manually doing this operation.0214

Now that we have a function that does it for us, that simply gets replaced with a function call.0217

Now, we have currItem, and we call getImageFilename.0223

And here, you notice that this is the syntax we use for calling object methods; it is the dash followed by a greater than sign,0227

and then the method name followed by parentheses, with nothing in between them if there are no parameters that need to be supplied to it.0233

And so, one thing you can see already is that it cleans up our code a little bit.0241

So, instead of having this mess everywhere within our code, now we have it in one file name.0244

And all of that ugly code is consolidated to this one spot here, within our Item class.0250

Additionally, we can see that, because we have included this in the one spot, we can reuse this, as we always do when we create functions.0258

One of the goals of creating functions and methods is to reuse them.0266

So, if we look at our insertItem function, one of the things that the insertItem function does 0270

is moves an uploaded image file from the temporary directory to the images directory.0280

Part of what it needs to do that is the file name of an Item's image.0285

As you can see down here (here it is), we have the call to move_uploaded_image.0292

And then, one of the parameters that move_uploaded_image takes is the image name of the Item.0306

And so, here we can see: we use this getImageFilename object method on this particular Item that you are inserting into the database.0313

So, as before (if we looked at the old version of this, insertItem in our last version), you can see down here that0323

here we have that same concatenation operation done here in hand.0337

We have this ugly code, and now we have replaced it with a simple function call.0342

We have been able to reuse the functionality; we have been able to clean up our code a little bit.0348

Another thing that having object methods does is: it provides you the ability to change things.0353

So now, let's say we had an architectural decision, and decided, "We don't want to call the name of an Item's image its ID plus the file extension."0358

Maybe we want to call it the Item's name plus the file extension.0373

Well, then, in every spot in our code, we would have to go in...0376

For example, here in insertItem, we would have to update this so that here, it would access the Item's name.0379

And then, we would have to go to Item.php, and we would have to update this here, so that it would say current item name.0389

We have to replace that in every spot that it is used.0398

Well, now that we have incorporated this into a function, we don't have to change that function call at all.0401

All we can do is just go change that function's definition.0406

We could go to (let me pull up the code for it) our Item.php class.0409

And right now, it returns the itemID; all we would have to do would be to change one line in here to name.0424

And now, every time a function needs the file name of an Item's image, it is going to get the correct version.0429

That is another advantage of using object methods.0437

And as with any functions, we can consolidate the functionality to one spot.0440

And then, if we need to update it, we only need to update it in one spot; so, that is one of the advantages of that.0447

For our Department object, we have added three different methods.0454

The first two are addItem and removeItem; and what they do is: as we know with our Department class,0457

it has a property that is an array called items, and it is an indexed array 0464

that contains the item ID's of all of the items in that particular department.0469

Well, we are creating these helper methods that are object methods that you can call on a Department.0473

For example, you can call addItem, and you can pass it a value of, say, 1001; that is saying, "Add item 1001 to the Department."0479

This method will go and know how to update the items property of that particular object,0487

so that item 1001 would now be added to it.0496

removeItem does the same thing, except that it removes a particular Item that you pass to it from an Item Department.0499

We don't make use of that right now, particularly in our script, but because we have added the addItem functionality,0506

we are going to add the removeItem functionality, too, because it may be something that we are going to be using in the future.0511

And it also shows another example of looking at object methods.0516

If we go and look at our addItem method in our Department object (oops, go to the right version),0522

we can see that what it does is takes an item ID, and then (I'll get to this in a second) it tests to see if the Item is in the Department.0534

And then, if it is not, it goes and adds the item ID to the items property.0542

Here again, you can see the $this variable, that special variable, that is going to say,0548

"When this addItem method is called, on whatever Department object instance it is called on,0553

I want you to add the itemID to that object's Items array."0561

removeItem does the same thing, except it just unsets, using the unset construct in PHP to remove a particular Item from an array.0568

And it does that by searching through the Items array in that particular object.0580

Now, one thing to note is that the other method that we have added to this class is called isItemInDept.0587

And if we look down here, it is a simple function: you pass it an item ID, and it tests to see if that item ID is already in that items array for that particular Department.0595

So, essentially, it is just testing if that Item is already in that Department.0610

We are making use of this PHP in_array function, which tests for a value in an array.0614

And we are saying, "Does the value that we are passing to it (itemID) exist 0619

in the items property array of this particular object instance that we are working on?"0624

When we call addItem, say, with string 1001, the first thing we do is: we call this method.0630

And here is an example of calling an object method from within another object method.0638

We are saying, "On this object, call this isItemInDept method, and see if the itemID we passed to addItem is in the items array."0642

Now, the key thing here is that it uses this $this keyword, so that, whenever this method addItem is executed0652

on a particular object, it is only going to test for if an Item is in that particular instance of the Department.0663

Remember, with the $this variable, it refers to a particular instance of an object.0672

So, each time this method is run on a different object, the values in that items array could be different.0677

This isItemInDept function may return true or false differently, depending on the values of the items array in that particular instance of that particular object.0685

That is the addItem function and the use of the isItemInDept function.0699

One of the places that we have used these is in our addItem function, which adds an Item to our store database.0707

And then also, we have used them in addItemToDept and buildDeptObject.0715

Let's go take a look at the addItemToDept function.0726

And I misstated: the addItemToDept function uses this new function, addItem, we have created, as well as this isItemInDept function that we have created.0732

If we go look at our addItemToDept, we can see that...0741

Well, first of all, let's look at the old version of it.0747

What we used to do is: we would load a Department from the database, using this getDepartment function.0750

We would check to see if the particular item ID specified to the function was in the function, by looping over this items array.0758

And we did that using this object accessor syntax.0767

And then, if it wasn't in the Department, we went ahead and added the item ID to the items property of that particular Department.0773

Here is an example of the square bracket syntax for accessing or adding an element to an object property that is an array.0782

Well, now what we have done is: in our updated version, our test is simply:0790

we had to test to see if the Item is already in that particular Department.0796

After we load the Department up, we just call this function we have created, isItemInDept,0800

which is going to test to see if that item ID is in the Department.0805

If it already is, the function is going to return true, because addItemToDept (if you remember) 0809

returns true if the function is successfully added to the Department, or if it is already in there.0814

If this returns false, then we are going to go ahead and add the Item to the Department.0819

And before, we did that directly, using this array syntax.0823

Now, we do it using the addItem method, and we specify itemID.0829

Now, again, the one advantage we can take from using these object methods is...0836

Well, let's say, for example, we wanted to do some verification on an item ID, because in this case here, let's say0847

maybe somebody else writes some code that wants to add an item ID to our items property of a particular Department.0855

Well, they can add an item ID that is an invalid ID; let's say item ID's have to be strings comprised only of numbers--they can't have letters.0864

Well, with this, they could go ahead and directly add an item ID to this items array that contains letters in it.0871

Well, now, calling this addItem function--requiring that to be used to add an Item to a Department0883

(and we will see more about requiring that when we talk about getters and setters),0891

what we can do is provide some validation within addItem.0896

So, we could go and...let's look at our new version of Department.php...where we have our addItem array...0900

Well, first of all, we do a little bit of validation: we test to see if the Item is in the department, so that is one thing.0915

And if it is not, we add it to there.0921

But also, we could perform some other tests in here.0923

So, let's say, we could perform a test that would say, "If this contains any letters in the item ID, then don't add it to the items array."0925

So now, instead of having to perform that testing everywhere that we want to add an Item to a department,0940

we can include it in this function, and it will get run every time that this addItem object method is called.0948

That allows us to, any time an Item is (attempted to be) added to a department, perform some validation on it.0957

And we can include that all in that class definition.0965

We can include that validation, as opposed to maybe having it perform a check here that says, "Are there letters contained in here?"0967

and then, any time else we used the addItem...maybe we used it in another function 0974

where we would want to add an Item to a department--we would have to perform that same check--0978

we can include that all in the addItem function.0981

One thing that I wanted to note, also, is that a default value needs to be set for our items property of our Department object.0988

If you look at our Department class definition, you can see that we have set a default value here.0997

And we learned, in our first lesson on objects, that you can do that.1004

And we did that because, in order for this isItemInDept to work on newly-created objects, 1009

you have to have a default value set, or else you are going to get an error.1018

So, we set that up here; that is just one thing to note.1021

We are going to be addressing that in our next version of the application, when we are going to learn about what constructors are.1024

So, we are going to move the initialization into what is known as a constructor function.1030

But I just wanted to mention that to you--that we have added that initialization.1034

And without that, there are going to be errors that will show up when you try to call these functions.1037

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1045

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be covering the topic known as object constructors, which are a special type of object methods.0005

We are going to go over what an object constructor is.0012

We are going to talk about how to define constructors within your class definitions.0016

We are going to talk about how to specify arguments to constructors, and then just go over some important notes,0022

as they relate to using constructors in PHP.0028

In object-oriented programming, a constructor is a special object method that is called every time you create a new instance of an object.0034

For example, if we go back to our typical Person class, every time we create a new instance of the Person class,0045

using this new keyword, a special object method for the Person class, called a constructor, gets executed.0057

And it is done automatically by PHP.0066

It is a special kind of method; you don't actually have to define one, but if you do (which is what we are going to go over in this course),0071

it has to have this special name here: and constructors in PHP 5 (which is what we are working with) are known as magic methods.0076

And that means they have some special meaning in PHP.0087

In this case, it means it is something that PHP knows to call automatically.0089

And any time you see a method with two underscores before the name of it, that is reserved as a magic method.0093

And we will talk more about that in a future lesson--about what magic methods are.0099

For example, let's take a look at Person.php.0104

And we are going to go more into the details in a second.0110

This is an object method that is a constructor for this Person object.0112

It is defined just as you would any other method, except it has to have this special name.0120

It has to have this name: two underscores, followed by the word construct, and then parentheses.0124

And just to show you that inside our constructor, it doesn't do anything: it is a function that can do pretty much anything other functions can do...0129

We are going to echo a statement that says we are inside this Person constructor,0137

so we know that this method is being executed--because we never actually call this construct method directly.0140

So, to let you know what is going on behind the scenes, we are going to demonstrate that.0149

And all we are going to do is: in this simpleConstructor.php script, we are going to just instantiate a new instance of this Person class.0153

Now, because we have defined a constructor for it, PHP is automatically 0162

going to run that constructor every time this new keyword defines a new instance of the class.0165

And because that constructor is going to get run, it is going to output the message.0171

If we go and look at this script simpleConstructor.php, we can see that it outputs the message "inside Person constructor."0176

Even though we never actually explicitly called, for example, Person __construct, like we would another object method,0188

it gets done every time this new statement is executed.0198

Constructors can be defined just like any other object method.0208

As we mentioned, they have to have this specific name here to be called automatically.0211

One thing they can't do is return a value; but as far as methods go, they can do the same thing, pretty much, as other object methods and functions can do.0216

They can accept parameters, and they can perform operations within them.0225

Typically, a constructor is used to perform initialization tasks that need to be done before an object is ready to use.0229

For example, when you have properties defined in a particular object, because that constructor gets called0239

every time a new instance of that object is created, you can use that as an opportunity to set default values for your properties,0245

or to maybe perform some other advanced functionality that you might need to do before a user can really use that object.0255

If we take a look at a new version of Person.php (which, again, just has a firstName and lastName property), here we have defined the constructor.0264

It takes no arguments; and we will talk about ones that can take arguments in a second.0278

And what this object method, this constructor, does, is: it initializes our firstName and lastName variables, just so that they have default values.0283

It is just going to initialize them to the empty string.0292

So, at least that way, if someone calls new Person, and then tries to access these variables,0295

it will at least return a string (in this case, the empty string), because a user of the Person class would be expecting a string to be returned.0301

If you will notice, again, as we have done in our other object methods: to access an object's properties from within an object method,0310

which a constructor is, you use the $this special variable.0317

So, if we go to our script called noArgConstructor, what it does is instantiates a new Person class.0322

And we don't do anything else with that Person; we don't set the values of any variables or anything like that.0331

We are not making any statements like this.0338

All we are doing is instantiating the class; and by default, that is automatically going to call that default constructor.0345

And then, what we are going to do is: down here, we are going to try and output those variables--those object properties, firstName and lastName.0352

Now, because this constructor has been called, they get set with the default variable of the empty string.0361

I just have a little test that we have created down here that tests if this instance of the Person object's firstName is equal to null,0366

which means it hasn't been initialized, because that is a default initialization value for variables in PHP.0380

Then, it is going to return the value of firstName.0387

Now, what it is going to do: this is a ternary operator, and it is going to set this firstName variable equal to that firstName value.0390

So, in this example, firstName has set a variable; it is set to the empty string.0398

It is not a string that has anything, but it is set to a string, so it is not null.0403

And otherwise, this is going to return the string null.0408

When we output firstName, if firstName hasn't been initialized, it is going to output null.0412

If it has been (which we know it has, from our constructor), it is going to output the empty string.0416

And we do the same thing down here for our lastName.0421

If we go and load this script in our browser, noArgConstructor.php, we can see that, when it tried to output firstName and lastName,0423

it output the empty string; and so, that means that the values were not equal to null.0434

Let's say, instead, that in our constructor, we didn't initialize, for example, the lastName variable; let's say we just removed that.0440

So, we only initialized firstName.0448

Because of that, lastName is never going to be initialized; it is not going to be a string; it is going to be set equal to null.0451

When we run our script, we are going to see lastName, and it is going to output the value null.0456

And so, that shows using a constructor to initialize variables.0462

And pretty much, that is what you are always going to want to do with your constructor.0468

You always want to give, for various reasons, default values to all of an object's properties.0471

And the main place you do that is within the constructor.0480

And we are going to see a little bit more about that on our next slide.0484

One thing that we noted is that constructors are methods; in that way, they can take parameters, just like any other object method or function can do.0491

And the way you provide objects to an object's constructor is by specifying them in between the parentheses0500

when you instantiate a new instance of the object.0508

Normally, when we call an object method, and we want to pass it two parameters, we would call the method name, and then pass it the parameters.0514

Because this is done automatically in PHP, what PHP knows to do is that, if you provide any parameters0527

between the parentheses in a statement where you are instantiating a new instance of an object (in this case, the Person object),0534

whatever is in parentheses are going to be passed as parameters to that constructor object.0542

So, you can define constructors that can accept multiple parameters.0546

They are placed in a comma-delimited list, just like any arguments you would supply to any other function or object method.0550

The only difference is just that you are not actually calling the method by its name; you are just using the name of the class.0558

And PHP, again, knows how to automatically pass those variables on to the construct method.0564

One thing that this is typically used for is, for example, our Person object.0571

The Person object has a first name and a last name; what you can do is use a constructor that requires two parameters.0576

And so, whatever values you pass it, it can use to set as the firstName and lastName of that Person, which is what constructors are commonly used for.0583

For example, if we look at our new version of Person.php, we can see that we have an updated constructor0590

that takes two parameters: one called firstName and one called lastName.0599

And then, it sets the value of our object property, firstName, equal to whatever value was passed in by the firstName parameter.0603

And it does the same thing for our lastName property: it sets the lastName property of this instance that this constructor is being called for.0612

And it sets it equal to the value that is passed into the constructor via lastName.0621

For example, now, when we call our constructor for Person, we can pass it two parameters.0628

We can pass it a first name and a last name--in this case, Joe Smith.0634

And now, what we can do is: we are going to output things, the same as we did before.0638

We are going to test if firstName is equal to null and if the lastName property is equal to null.0642

And if not, it is going to store, in the value of firstName and lastName, the values of those firstName and lastName properties, respectively.0646

And if not, it is going to return null.0653

Now, because, when you call this constructor, it is going to set these values for the firstName and lastName properties,0655

when this ternary operation occurs and these echo statements occur, 0662

it is going to output that firstName and lastName we provided to the constructor.0668

If we run this script as is, we can see that it outputs that firstName equals Joe and lastName equals Smith.0673

Now, in our previous version of Person, we had a default construction that didn't take any parameters0682

and just set the default values to the empty string.0687

In that example, if we wanted to set the firstName and lastName properties of that Person object,0692

we would have to say like "firstName='Joe'" and we would have to call it in a separate assignment statement.0700

So now, when we go and run this version of (actually, let's do a different name, 'Joe Jones,' so we can see there is a difference)...0720

and we go back to our last script, the noArgConstructor, we can see that now it outputs Joe and Jones.0731

But we had to go and use these two separate assignment statements.0738

What this new constructor that accepts parameters does is: it allows us to create a Person and set the names of some of its properties,0743

without having to call separate assignment statements; that is one of the nice things that you can use a constructor for.0754

And then, one of the key things with constructors is that, if a constructor does take, for example, two parameters0762

(our Person object, in this case--the constructor takes two parameters), you have to pass it all of those parameters.0770

So, let's say we leave out one of them, and we run our script.0777

We are going to get an error from PHP, saying there is a missing argument for our constructor method.0783

It is saying that you have to provide argument values for all of the parameters of a particular function.0798

Now, as mentioned, a key thing that a constructor does is set default values for properties.0812

In this case, our constructor requires two parameters; so, our firstName and lastName always get set, every time that constructor is called.0821

In our last example, where we didn't accept any parameters, this one causes problems if you don't properly initialize things.0829

Let's say we had a new property to this Person class called arr1, which is going to represent an array.0839

And let's say that, in our constructor, we don't initialize it.0849

We'll go ahead and initialize firstName and lastName, as before.0856

And when we go ahead and run this noArgConstructor script, it is going to run (let's get rid of these) fine, and it works as functions.0862

However, because users of our Person class will know that it contains an array as one of its properties, maybe they will try to access that array.0879

For example, maybe they will run a test that tests for a particular value in that array.0893

For example, they will call in the Person object; they will access that property, arr1.0900

And they are going to say, using the in_array function, for example, "Is the string 1 within that array property of the Person object?"0907

Now, because that hasn't been initialized, this is going to cause an error.0924

So, if we go ahead and try to load this now, it's going to say, "Warning: in_array() expects parameter 2 to be array."0928

This is an example of some of the problems that come up when you don't initialize the properties of your class.0935

The way you would handle this would be to go ahead, in our Person class, in the constructor,0943

which is the place to do this, and say arr1 equals empty array.0949

So now, it is definitely an array; it is an empty array, but at least it won't cause problems when other code tries to access it as an array.0956

Now, when we run our script, it is not going to throw any problems, because it is actually an array data type.0964

A couple of things to note: as you have seen in our web application example, a class is not required to have a constructor method.0974

We haven't actually had that, for example, in our Item and Department objects within our web application.0981

However, if it is provided, PHP will automatically run it for you.0988

As mentioned (to mention it again), it is good practice to make sure that all of an object's properties are initialized.0992

And you can do that in the constructor method.0998

And then, one thing to note, for those of you that have used other programming languages, is:1001

unlike other programming languages, in PHP, you can only have one constructor defined per class.1005

A lot of other languages allow what is known as constructor overloading, where you can have different constructors for an object that take different parameters.1009

And depending on how many parameters, for example, you put in parentheses when you are declaring an instance of an object,1017

the other programming languages, will call different constructors, based on how many parameters are provided.1033

So, you can maybe have two constructors: maybe one of them takes one parameter, and one of them takes two.1040

Well, on PHP, that is not allowed; so for those of you that are familiar with that in other languages, that is not something that you can do in PHP.1047

For the homework challenge, what I am going to have you do is update something that you did in our last homework, which is our HttpRequest class.1056

The first thing I am going to have you do is create a new property for the class called method.1065

And method is going to be an integer that can have a value of 0 or 1, to represent whether this HttpRequest is a GET request or a POST request.1070

If the value is 0, it is a GET request; if the value is 1, it is a POST request.1079

Then, what I want you to do is alter the getRequest method so that, when it outputs that first line of HttpRequest1086

(for example, GET /index.html, HTTP /1.1), it is going to test the value of this method property.1092

And if it is a 0, it is going to use the GET method; it is going to output GET /index.html.1101

If it is a 1, it is going to use the POST method; it is going to say POST /index.html.1105

Update the getRequest method.1111

Then, I want you to add a constructor (and that is what we are going to take from this lesson today) that takes two parameters.1114

The first one is going to be the uri property.1120

As you remember from our HttpRequest class that you were to design in the last homework, 1124

the HttpRequest object has a uri property that represents the URI for this HTTP request.1130

So, you are going to pass in a string; the constructor is going to take a string that is going to set the uri property.1139

It is also going to take an integer, a 0 or a 1, that is going to allow you to set the method property.1143

When we create this HttpRequest, we can set its method and its uri, all by calling the constructor.1149

Make sure, also, that your constructor initializes the headers property.1156

You are probably going to want to do it to an empty array, because headers, as you remember, is an array.1163

That is what we are using it as within our HttpRequest class.1168

And the constructor is a place where we initialize object variables, so we are going to give it the default value, typically, of an empty array.1175

So, make sure you do that for headers.1182

And then, I want you to go ahead and create an instance of this new updated HttpRequest class,1184

where you supply it both some random URI (like /index.html), and then a 1 that is going to set the method property to the POST method.1190

Go ahead and add a Host header to the object, using the addHeader method.1203

And then, call getRequest on that object, and output its output between pre tags.1208

And then, verify that your output has the format here.1214

If it is implemented correctly, you should see that POST is output as the method of this request, 1217

because we passed it a 1 when we created the instance; and also, that it has a Host header on it, as well.1224

And the value of that can be whatever you pass to it.1233

But the main portion for this lesson is about the POST.1235

Then, what I want you to do is alter the constructor so that, if a value is provided for method...1239

because it is a parameter required for that constructor, I can provide a method with a value that is a string 'A.'1245

Well, that is not a 0 or a 1, so that is not useful to us.1252

So, in the constructor, if the value provided for the method property is not a 0 or a 1, then it is going default1255

and set the value method equal to 1, which, in this case--the default would be the GET method.1264

So, this is an example of how you can also use your constructor to make sure that your objects start off in a well-known state.1270

You can perform some error checking; so, instead of being able to set...1277

all of your functions (for example) in your HttpRequest object are going to be expecting a 0 or a 1 as a value for method.1282

Well, by using the constructor to ensure that method only gets set to a 0 or a 1, 1290

you are going to make sure that those other functions are going to work as expected.1297

Then, to test out that this new constructor that tests method to make sure it is a valid value works,1302

go ahead and create another instance of the class, but this time providing the integer 5 as the method argument.1310

And then, verify that now, when you output the request using the getRequest method,1317

it actually has the GET method listed in the request.1322

And that is because your constructor should, by default, if a 0 or 1 is not provided, default method to 0, which corresponds to the GET method.1326

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1335

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application, incorporating what we learned in our last lesson on constructors.0005

In today's lesson, we are going to be providing an overview of the new version of our web application, which uses constructors, which is version 7.0.0013

And then, we are going to go over all of the different constructors that we have created.0020

We have three classes that we use within our web application: the Item class, the Department class, and the Customer class.0024

And we are going to discuss how those constructors work for each of those classes, and how they are used within the web application.0033

As mentioned, for this version, 7.0, constructors have been created for all of our objects that we have (Item, Department, and Customer).0042

And everywhere where we have created instances of the objects, before we used the new statement.0053

Now, we are using the constructors that we have created.0063

And all of our constructors, as you will see in a minute, take arguments.0065

Whereas before, for example, we were just creating a new Item with a statement like this, with something over here or a variable,0069

now, because we have created constructors that take arguments, we will be creating instances of objects using this syntax over here,0078

where we will actually be passing argument values to our constructors.0092

And that is something we learned about in the last lesson.0095

Additionally, for all of the constructors we have, we are providing the ability to set all of the different property values for that object.0099

For some of our constructors, values are not known.0108

For example, when we create a new Item object from our addItem.php page, we don't know what the itemID 0111

and the image file extension are yet, because those get extracted and created in the insertItem function.0120

When we initially create these Item objects, we are going to be passing null for some of the parameters, because we don't have values for them yet.0129

The Item class that we have--we have created a constructor for it, and it takes arguments for 0141

each of the different properties that the Item class has, like itemID, name, price, description, and so forth.0147

And the way we work inside the constructor is: if any properties are not supplied to the constructor, or they are empty,0155

then we just set those properties to a default value of an empty string.0163

And if you remember from our lesson on constructors, that is part of what constructors are used for: to set up an initial state of a particular object.0166

And in this case, we are making sure that all of our values for an Item class have at least a basic value set.0175

Let's take a look at the Item class in a new version, 7.0.0186

And we can see that we have created a constructor (let me blow this up a little bit), which, as we know,0195

is a magic method, which is named __construct.0201

And as we can see, the signature, or the prototype, for this method is to take 0207

a string ID, a string name, a float price, a string for the description, and a string for the image file extension.0214

And if we go down and look at our constructor here, this is the body of the constructor.0222

All that it does is goes ahead and, using the $this keyword (which we know allows us 0227

to get access to a particular object's instances' properties), we are going to set (for example) the item ID.0234

And if an item ID is passed in (so it is not empty), we are going to set it equal to the item ID passed in.0243

Otherwise, we are going to set it equal to the empty string.0248

We do this for all of our different variables.0250

And what that does is at least gives them a baseline value; for example, they will all at least have an empty string value, so that they are at least initialized.0254

The different places that this new Item constructor is using: the first place, for example, is in addItem.php.0268

So, if we take a look at addItem.php, and we look at the old version (which would be version 6.0),0274

when we create an Item object in the data processing section, we previously had just used the new statement that said new Item().0283

And because we hadn't declared a constructor before, no constructor gets called.0293

So then, what we would do afterwards is manually go ahead and set each of the different properties of this new item--0298

for example, the name, the price, and the description.0303

Well, now these statements can all be incorporated into one constructor method call.0306

So here, we say new Item, and we have our parentheses as we normally do when we are declaring a new instance of an object.0314

But now, we can provide argument values for all of the parameters of the constructor.0321

If you look back at our documentation for the constructor, we can see that it takes five different parameters for each of the different properties.0327

Because of that, we have to pass it five different parameters.0336

In this case, right now, because when we use our addItem form, we haven't generated an item ID yet, it has to be gotten from the lastAdded file.0339

And we haven't gotten the item's image file extension, because we extract that from the image file that gets uploaded.0348

We do that in our insertItem function.0355

We only have the name, price, and description for which we can specify the constructor.0359

But because it takes five arguments, we need to provide values for the other ones.0364

And in this case, one of the standard ways of doing that is just providing the value null.0367

So, this creates the Item object and sets these three properties.0372

And it does the same thing as this here, because of the way our constructor works.0377

The other spot that we use our new Item() constructor is in buildItemObject, which is a function in our file library.0384

If we go look at buildItemObject, we can see that what we do is: again, here is an example of our new constructor.0392

It has the opening and closing parentheses, and then, in between it, it has five different arguments.0402

In this case, when we use this buildItemObject class, we are building an item up from data fields that were extracted from a line in our items data file.0407

So here, you can see: for example, for the item ID, we are pulling the first data field from a line in our items file, and we are running the trim operation on it.0417

And this allows us to go ahead and set the ID, the name, the price, the description, and the image file extension for this particular item.0428

Now, because we are pulling this buildItemObject function to build an item object up from a file in our items text file in our database,0435

that items file already has all of the information about a particular item.0449

So, you don't have to use null here for either the item ID or the image file extension,0454

which is why all 5 of the parameters to this Item constructor are passed values.0459

We have basically done the same thing for our Department class: we have created a constructor for it.0469

And it takes arguments for all of the different properties that a department has: its name, its department ID, and the items,0474

which is an indexed array of all of the item ID's of the items in the department.0482

What we do in the constructor is: for the deptID and name property, if those are not passed a value when the constructor is called,0488

they get set to the empty string, which is similar to what we did in the Item class for any properties that were not passed values.0497

For example, if we pass in the value of null, that is considered empty; we are going to set a value for the properties0503

equal to the empty string, just so that they have at least an initialized value.0509

Additionally, if the items property is not passed in (if we don't pass in an indexed array of item ID's that represent items in the department),0514

then we are going to be initializing items to an empty array.0524

And that is because it is an array property, and so, when we initialize it, we want to initialize it to a data type that it is going to be used as.0528

In this case, it is an array, so we use the empty array.0538

If we quickly take a look at the constructor for our Department class, we can see that we have construct.0542

It takes a deptID, name, and items parameter.0551

And what it does is: as said, it sets the department ID and name equal to whatever values were passed in, if they were passed in.0557

Otherwise, it sets them equal to the empty string.0564

And then, it also tests if items was passed in; and it also performs an additional test.0566

If items is an array, then it goes ahead and sets items to the array that was passed in.0572

Otherwise, it just sets the items property equal to the empty array.0576

This is another example of one of the things that the constructor allows you to do.0581

When you create an object, it allows you to perform some data checking on any information that code provides to your particular constructor.0585

What that allows you to do is make sure that your object stays in a state that you understand, and that you know about.0596

For example, if we hadn't checked this is_array, we could have passed in a string here.0602

And then, if we just ran the test to see if it was empty, then we would be setting our items property--0608

we would be initializing it to a string value, when, in fact, it should be an array.0614

This is an example of how we could use a constructor to make sure that our object always starts off in an appropriate state.0618

And like with the Item constructor that we created, we use our new Department constructor in the buildDeptObject function.0626

If we take a look at that, what we can see is (I'm trying to make it a little bigger) that, when we build our department object,0637

we call the constructor, and we provide it a department ID and a name.0650

And in this particular case, we use buildDeptObject again to build a department object from a line in the departments.txt file.0656

And the way we do that is: we initially pull the department ID and the name for the department and set it in the department object.0663

Then, what we do is loop over that last data field in departments.txt, which is a comma-delimited list of all of the item ID's in the department.0669

So then, what we do is use the addItem function (if you remember) 0678

to add each of those item ID's to the items array of the particular department we are building.0682

Because we essentially do that after the department is already built, for the items parameter of the departments array,0690

we initially pass it the value of null; and that is kind of like what we did for the items array.0696

Then, what we do is loop over all of the item ID's that are part of that third data field in each line of departments.txt.0702

And then, we use our department addItem function to add each item ID to the items array.0712

And if we go and look at that again, we can see that all the addItem does is checks to see if an itemID is already in the department;0718

and if it is not, it adds that to the items array.0733

So, between the combination of using the constructor and then this addItem function, we are able to build up our Department object.0735

The last class that we currently have in our application is the Customer class.0745

And we have created a constructor that takes arguments for all of the properties of that class:0749

first name, last name, street, city, apartment, and so forth.0754

And for any properties that aren't supplied when we call a constructor, we set them to the empty string.0757

And again, that is just part of using the constructor as a way to initialize all of the properties of our new object,0762

to make sure that it is in a well-known state.0769

And if we take a look at our Customer class, we can see that we have the constructor method that takes 0773

7 different parameters for each of the properties (as you can see here)--the string properties that are part of a Customer class.0783

And if we look down at our construct method, it looks very similar to our item class, in that it tests to see if any particular parameter passed in was set.0792

If it is, it sets the object's property value equal to the value passed in; otherwise, it sets it equal to the empty string.0802

And the place that we use this new constructor is in checkout.php, which is where we 0810

build up this Customer object from the data a user submits when they are checking out on our web application.0815

If we go and look at checkout.php...first, let's look at the old version, version 6.0.0822

We can see, in the data processing section, where we are completing the order0828

(which is after the user has entered all of their shipping information), that what we did in the last version was:0831

we created a new Customer object, a new instance, and we used this default syntax.0837

Because we hadn't defined a constructor, no constructor, in this case, is able to get called.0844

So, what we have to do then is manually go ahead and set each of the different properties of this new Customer object.0850

And in this case, we are doing it from data that was passed in by the POST method.0859

So, we are accessing this custData associative array, which contains all of the information about our new customer.0864

Now, in our new version, we have done the same thing, except we have incorporated this all into one statement.0871

It is a call to the Customer constructor.0877

So, instead of just calling Customer with two parentheses, as we did before, we call it with parameters.0880

And what it is doing is passing the firstName, lastName, street, apartment, city, state, and zipCode, all to that new Customer constructor that we created.0886

And then, that constructor is going to be able to go ahead and set all of the properties of that particular Customer object.0896

And so, now we have turned it into this one statement that created a new instance.0903

And then, all of these other setter statements for setting each of the properties are now combined into one constructor method call.0910

And because it does that, that would also allow us to, within the constructor, make sure that valid values were passed in.0921

For example, if we wanted to make the application a little more robust, we could do things0928

like to check to make sure that the zipCode is a valid ZIP code.0933

We could check to make sure that the state is only two characters, and it is a valid state abbreviation, and so forth.0936

And so, again, to reinforce: that is what the purpose of the constructor is--to get your new object that you are creating initialized,0945

and get it in an initial state in which it can be used, where all of the data contained in it is valid data.0952

Or if no proper data was provided, it at least has default values that you can work with in other functions of that class.0960

That is how we used all of these different constructors within our web application.0970

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.0974

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be discussing the topic of magic methods again--0005

which, as we learned in our constructors lesson, is a special type of method in PHP.0009

We are going to be specifically getting into a few more details about what magic methods actually are in PHP.0015

We have used them before (when we talked about a constructor, that is a magic method in PHP).0021

But now, we are going to provide a more formal definition of that.0025

We are going to talk about what are known as destructors, which, in PHP, is a special magic method.0028

Then, we are going to talk about three different magic methods in PHP: __toString, __get, and __set.0035

And then, we are also going to talk about the concept of access modifiers, which relates to declaring, for example, all of our properties and functions.0046

So far, I have the public keyword listed before them.0055

We are going to talk a little bit more about why that is, and how we are going to change that.0058

And then, we are going to finish up talking about using getters and setters in general (which are ways to get and set properties of a particular object).0062

In PHP, any method that starts with this (which is a double underscore) is known as a magic method.0073

And any time you create an object or a class file, you shouldn't create any methods that begin with an underscore,0081

because PHP reserves the right to, in the future, use those as magic methods.0089

In particular, for example, we know that __construct is a magic method; so, you wouldn't want to define your own construct method0094

in a PHP class, unless you were actually planning on using it as a constructor,0105

because otherwise, PHP is going to treat it as a constructor, and it is not going to be something you could run on your own.0109

Magic methods are special in that they are automatically called by PHP.0118

For example, we know that a constructor...whenever we use a new statement (for example, new Item) and pass it some data,0123

this construct method is implicitly, automatically called by PHP.0135

And that is why you don't want to name methods construct--because then, for example, if we had an Item object,0140

you wouldn't really be able to call that construct method.0149

And there are a number of different magic methods that are available to objects in PHP.0155

And we are going to be talking about a number of those different ones that are available in today's lesson.0160

First of all, I want to talk about the concept of a destructor.0167

It is the analog to a constructor: a constructor is called automatically when a new instance of an object is created.0170

On the other hand, when an instance of an object is destroyed (which means that it is no longer being used),0178

you can have a method, that is called a destructor, that is called.0187

And what that does is: it is used to clean up any object state before the object is destroyed.0189

For example, maybe you have some open files that were used by a particular object.0196

By having this destructor method that always gets called--and it is something that, if you define it,0202

always gets called, automatically, by PHP, then you can ensure that all of your files will always be closed, 0206

which is a good practice so that you don't have file locking issues and stuff like that.0212

That is just one particular example; but it allows you to run any code that you would like to run every time an object is destroyed, before its lifetime ends.0216

And it is automatically called any time an object is no longer being used--0229

for example, when the script ends, or if an object is explicitly set to not be used0233

(which means you call the unset method, or you explicitly set it to null--that is telling PHP you don't need that object anymore).0241

When that occurs, the destructor is automatically called.0247

In PHP, destructors are magic methods, and they have a name similar to construct, except it's __destruct.0250

And it is within this method that you can define any operations that are code that you would like to occur whenever an object gets destructed by PHP.0259

For example, let's take a look at...we have a class here called DataFile that we are going to be building up during this lecture.0272

What DataFile is: it is a class that is going to encapsulate all of the things that we do for a file.0281

For example, we use fopen, fclose, and fwrite to open, write, and close a particular file.0286

Well, what we are going to do is wrap that functionality into this object called DataFile.0294

And what we are going to do, for example, is: for each DataFile object, we are going to give it a file name and an access mode.0298

And then, what you can do is: after you create this DataFile object, you can run an open function on it, which we are going to see.0304

Then, you can run a write operation on it, and a close operation on it.0312

And those open and close operations are calling, underneath the surface 0316

contained within the object's code, these fopen, fgets, fclose methods, and so forth.0322

That is what our DataFile class is going to be used for--to represent access to a data file.0329

In this first version, we are just going to give it one public property called fileName.0337

And as you can see here, we have our constructor function, which is a magic method.0343

that takes one parameter, and it just sets the value of our fileName property.0350

We also have an echo statement here; and this is going to be used to show how PHP is working behind the scenes.0355

It just says, "OK, we are in the DataFile constructor."0359

And then, here is a new magic method, the destruct method.0363

And it just simply outputs a message that says that we are in the destructor.0368

We are going to be improving on this, so that this destructor method will close any open files that we may have open.0373

But for now, we are just going to output a message, so you can see at what point during a particular script the destructor gets called.0379

For example, we include our DataFile class in this particular script called destructor.php.0387

We output a message that says "before the object is created"; then we call the constructor, which is implicitly going to call the construct method.0393

So, we should see that output message from our construct method we defined.0403

Then, we output a message stating that this is the last statement in the script, and then the script ends.0408

And then, what we will notice is that another statement gets output.0413

It is the statement that is saying we are in the destructor, because when the script ends, the lifetime of this DataFile object0418

that we have created in the script is no more, and it is going to be destroyed.0424

And so, PHP automatically calls the destruct method.0428

So, if we run this particular version of destructor.php, we can see that we have a statement "this is before the object is created."0431

The next thing that happens is that you are inside the constructor.0442

Then, you can see that we execute the last statement in the script.0445

And yet, even though we have executed the last statement in the script, we have another piece of output.0449

And it says "inside the DataFile destructor," so that shows you that, when that script ends, if any objects still haven't been destroyed yet,0454

the destructors still get called; and so code is actually running, even though we are not in the script anymore.0461

An alternative version to that is: here we have the same DataFile class in this new version, but what we are going to do is:0468

instead, we are going to say to output the message that says "this is before the object is created."0476

We are going to call its constructor, and then we are going to explicitly destroy the object by setting it equal to null--0482

which, as we mentioned on the slide, is essentially going to call that destruct method, because the object exists no more.0489

What is going to happen is: because the destructor gets called here, that message that says you are in the destructor0497

is going to get output before we get to this last output statement within our script.0501

So, the other of those last few statements is going to change.0507

If we go over here to version 2 of this, now we can see the output before the object is created;0511

we are inside the constructor; we are inside the destructor; and then, we execute the last statement in the script.0519

And the reason that "in DataFile destructor" doesn't occur afterwards, as well, is because the object has already been destroyed.0525

It has already had its destruct method called, and it was called when we set it equal to null.0531

So here, in this case, when the last statement of the script ends, the script actually ends, in that particular case--and no destructors get called.0535

What we are going to do now is have an updated version (it looks like...here it is...); this is version 3.0 of our DataFile class.0560

I am going to show you how I have updated it, because we are going to be using it throughout the rest of the lecture.0570

I have added a couple more properties to it.0574

I have added an accessMode property, which says you can set the access mode 0577

for which you want to open this particular file--this DataFile object it is going to represent.0582

There is a variable called fileHandle, which is going to hold a reference to the open file that this DataFile class represents.0587

And we are going to use that in the different methods within this class definition,0600

to open the file, close the file, write to it, and so forth.0605

Here, in the constructor (you can see that the constructor has been updated), it takes two parameters:0610

one to set the file name of the file that this is going to represent, and then also the access mode we are going to want to open it in.0615

And then, we initialize the file handle, initially, to null.0621

Then, if you will look down here, we can see that we have an open method.0626

It is an object method that you can call after you create an instance of the object.0630

And what it does is just opens the file that we have specified, using the access mode we have specified,0635

and then sets the object property fileHandle equal to the file handle that that returns.0641

Then, we have created another object method called appendLine, which is going to allow us to append a line to the data file this object represents.0647

And it uses the fwrite method.0657

And what we make use of is the file handle that we have created up here in the open class.0658

And then, it just writes whatever string we pass to appendLine to this file handle.0664

Finally, there is a close method; and the first thing it does is outputs an echo statement that says we are in close.0670

And you can see why we are doing that in a second: it is mainly for educational purposes.0676

It wouldn't be something we would normally do.0680

And then, you can see: we just use the fclose method within this objects close method.0682

And it closes the open file that is pointed to by this fileHandle object property.0687

And then, we go ahead and set the fileHandle object property equal to null; and there is a reason for that.0695

What we have is: our destructor has changed a little bit--we have a message that shows we are in the destructor.0703

But what it does is: we use the destructor to close the file that this DataFile object represents if it has not been closed yet.0710

What it does is checks to see if the fileHandle is not equal to null.0723

And if it is not equal to null, it goes ahead and runs this objects close method (which, as we saw, is down here).0727

And as we can see now, the close method, again--the last thing that it does is sets the fileHandle to null.0735

When the destructor is called, and it runs this test "Is fileHandle not equal to null?" that is its way of knowing whether the file has already been closed.0741

If it has already been closed, it doesn't do anything; if it hasn't been closed, it goes ahead and closes this method.0749

And this is our way of cleaning up this DataFile object, to make sure that the open file that it has, has been properly closed.0754

And let me open up...it looks like I accidentally closed one of the files.0765

If we look at destructor.php, this new version, we are including our DataFile class that we just talked about.0775

We are creating a path to a temporary file; in this case, it is just going to be a file called temp.txt in the current directory.0784

And then, we are going to create a new DataFile object using that DataFile constructor we just talked about, 0791

which takes the file name that we want to open, and then the method that we are going to use to open it in--0796

which, in this case...the access mode is going to be overwrite mode.0804

Then, we call the open method, which is going to call that fopen function that is going to open the file and set the object variable fileHandle.0808

We are going to append a line to it; in this case, we are just simply going to append a date/time stamp with a new line.0817

And then, we are going to call the close method on it to close that data file.0824

And then, our script is going to end.0830

In this particular order...when we run the script, we can see a couple of things.0831

We can see...if you remember, we had an output statement in our close method that says we are in the close method.0840

And we had an output statement in our destructor method that says we are in the destructor method.0846

In this case, you can see that "in close" has been output first; and that is because, in our file,0849

close was explicitly called; so that output statement that is in close gets executed.0858

And then, the file ends; the script ends down here.0864

And when the file ends, the destructor automatically gets called.0867

And when the destructor gets called, it is going to output that statement that it has in it that says "inside DataFile constructor."0870

And that is why that statement is output last.0876

Now, let's say that instead, in our main script, we didn't call the close function.0880

So, let's say somebody had written a script, and they didn't know how to use our DataFile object appropriately,0889

and so they opened it; they appended a line to it; but they didn't call the close.0896

Well, what is going to happen is: when the script ends, the destructor is going to get called for this class.0900

And because close hasn't occurred yet, our destructor is going to get run.0906

And it knows to close the file that has not been opened yet.0910

So, what you are going to see is that the destructor is going to get called.0914

You are going to see that you are in the destructor method.0916

And then, when we look at our destructor method, we can see that it also calls the close method.0920

Then, you are going to see this output statement that shows that the close method is being run.0928

These statements that we last saw are going to be reversed: where before we saw that 0932

we had the close method, and then we were in the destructor method,0935

now it is going to be reversed, because close was never called; the destructor gets called;0939

and then, the destructor, because the file is still open, calls the close method.0943

So, when we do that and refresh our page, we can see that they are reversed.0947

We are in the destructor, and the destructor, because the file is still open, is going to call the close method.0953

And so, that is a common example of how to use an object destructor to make sure0959

that any cleanup work that you need to get done before an object is destroyed actually gets done.0964

Another magic method that all objects can create is called __toString.0974

And what that does is: that is called any time you reference an object in a string context.0980

For example, let's say you create a new variable, a, and you set it equal to an Item.0986

You set it equal to an instance of an Item object.0996

Well, any time you were to use that object variable in a string context (for example, here within an echo statement),1001

this __toString method is going to get called automatically, if it exists.1015

And if it exists, it allows you to say how you want to output the particular object as a string.1018

For example, for an Item, we might have it output, as its string, the name of the item.1024

Whenever you would run echo name...let's say we had an Item class that is different from our web application.1032

It just takes one parameter that is the name of the item.1043

So now, when you would go to echo a (you are saying, "I want to echo this Item object"), 1047

the __toString method is going to get automatically called by PHP, and that is because it is a magic method.1052

And then, what would actually get output would be the string 'Basketball,' which would be the name of the object--1057

assuming our __toString method returns the name of the item as the string that it wants to represent the object as.1063

What you can do in this __toString method is represent an object in whatever string form you want to represent it as.1073

Let me close these files.1085

In this example we have...it is called toString.php, and it is basically the same as our last script example,1092

except that we are not calling any open or write operations or close operations on the particular object.1101

We are just creating a new DataFile object, having it represent a file called tmp.txt.1108

And then, what we are going to do is use the object within a string context.1118

We are going to just include the variable that holds the object instance of DataFile.1124

And when we put it in double quotes, PHP is going to know to call a __toString method on that object, assuming one exists.1131

Well, we have actually updated our DataFile class to include a __toString method.1138

And because we defined this method, we can describe how we want our DataFile object to be represented as a string.1153

In this case, our string that we are going to return is simply the name of the file,1161

followed by a colon, and then followed by the access mode, within single quotation marks.1166

Any time you include a DataFile object within a string context in an echo statement within another string,1171

the __toString is going to be automatically or implicitly called by PHP.1184

And it is going to output the name of the file, followed by a colon, followed by the access mode.1187

If we go and look at this in action, and we run the __toString script, we can see that our DataFile object is a string.1192

When it is output as a string (and we can see here that we include it during these HTML pre tags, so here we have included1203

our df, which is our object that represents a DataFile) it is going to call the __toString method.1212

And as you can see, what it does is outputs the name of the file that that object represents, followed by a colon, followed by the w.1218

We can do whatever we want within that __toString method to output a DataFile class.1227

For example, maybe we just want to include the file name.1233

So, if we change this, now any time we reference df, or any time we use a DataFile object within a string context, it is only going to output the file name.1240

And here, you can see, the w is gone.1254

And again, you can do whatever you want within this method; we could simply even (if we wanted to) just say DataFile Object.1255

Now, when we run this, it is just going to simply output the string DataFile Object every time we try to use DataFile object within a string.1267

That is how the __toString method works.1280

Now, one thing I want to talk about is something known as access modifiers.1285

What that refers to is: all object properties and methods have what is known as a visibility associated with them,1288

which describes where they can be accessed from.1297

For example, all of our properties we have declared so far in all of our classes have been declared public.1300

They have public visibility; they use the public access modifier.1308

If we look at our DataFile classes, we can see that we have used this public keyword here before all of our properties.1311

Now, what that does is says that anybody outside that class has access to that property--they can get or set that property.1323

You can also access it inside the class, using the $this variable.1332

Now, on the other hand, you could declare something as private.1339

And that means that it is only accessible within the class definition file.1342

So, you can only access it using $this within any methods within the class definition file.1346

If you try to access it, for example, in your script--if you try to access a private method, you are going to get an error from PHP.1354

There is one other access modifier, called protected, which we are not going to go over,1362

which says that any property that is listed as protected is accessible inside the class definition1366

(which means inside any of the methods within the class), or by inherited classes.1372

And we are not going to be going over inheriteds in this course, so it doesn't really apply.1376

So, we are just going to be talking about public and private access modifiers in this course.1380

The reason that you declare something as private is to facilitate an object-oriented method called data encapsulation.1388

What it does is: if you declare all of the properties of a particular object private, 1397

that means that any code outside of that object can't go ahead and directly change those.1402

And so, one of the foundations of object-oriented programming is that the object should be able 1407

to control and know everything about its state (all of its values), and make sure that it is kept in a consistent state.1413

That is why, in our constructor, for example, we initialize all of the object's properties in the constructor--1420

so that our object is in a known state.1429

Now, all of our objects we have used so far have had a public access modifier, which means that code outside the object could run it.1431

For example, we had talked, in our last web application, about the items array that is part of our Department object.1440

In our constructor for our Department object, we explicitly set that equal to an empty array1456

so that any time it is attempted to be accessed, it is accessed as an array, and it will be treated as an array.1463

That is how we want our class to function.1470

However, because items is declared public at the beginning of the file, anybody outside the class,1472

if they have a reference to this Department class (for example, maybe they have a Department object called department),1482

could go ahead and set items equal to the empty string, or any other string.1488

So now, our object is in an inconsistent state.1497

It has this items property that is supposed to be an array, but now it can be set to a string.1500

Our object methods that might count on the fact that that items property is an array might not work.1509

So, the way we handle this is by keeping all of the data in a particular class private.1517

And then, that way, any time you need to set (for example) pieces of data,1525

you either have to do it through a constructor (which is going to allow you to make sure that only valid values get set),1529

or through what are known as setter methods, or any other object methods that you describe.1533

Any time you want to touch the state (which is basically the values of the properties of an object),1538

you have to go through an object's methods; and that allows you to keep control over that data within that class.1544

One other thing is that methods can also be declared public or private.1552

And they have the same functionality that we described up here for object properties.1555

If an object method is public, it can be used outside of the class.1559

For example, on our Department class, we have a public method called addItem.1563

We pass it an item ID; that is a public method.1572

However, you can also declare a method as private, which means that it can only be used within the class.1577

So, if we declare a method as private--for example, if we declared addItem as private, 1582

when we tried to call this outside of the class definition, we would get an error.1586

If a method is private, the only way it can be called is by using the $this special variable, and then calling the function.1592

This applies for methods, as well.1603

Let's take a look at what a public version of our class looks like.1609

In this place, it is exactly the file that we had before.1617

We have all of our properties declared as public, all of our methods...1619

in this case, we have the three non-magic methods close, appendLine, and open--they are all declared as public.1626

And then, what we are going to do is create in our script a new instance of this data file.1631

And then, we are going to show that we can go ahead and set our object property values, 1636

using the regular accessor syntax, because those properties are declared public.1643

If they were private, we wouldn't be able to do this.1649

We are going to set the file name to change it from what was set in the constructor to index.html.1651

We are going to set the access mode to r.1659

And then, down here, what we are going to do is access these values.1662

Because these properties are public, you can use the regular accessor syntax in order to access those values from outside the class.1665

So, here we are going to access the file name in access mode, and we are going to output that.1675

When we run our script, we should get no problems, and we should be able to set those values and then output them.1678

And here, as you can see, we were obviously able to set them, because when we output them, 1688

they were output to the new values that we had specified, index.html and r, 1692

which is opposed to what they were initially set to, which was w and tmpFile.1696

So, as you can see, when properties are public, you have the ability to get and set them outside of a class.1700

Now, as an alternative to that, we have a private version of our DataFile class,1711

where we have declared all of our object properties with the access modifier private,1718

which means they can only be accessed from within the class.1724

And for example, you can see down here that they are able to be accessed using the $this variable,1731

because that is within a function within the class.1737

And the reason for that is because they are accessible within the class definition; you can access it with any of the class methods.1741

However, if we try to do the same thing that we did before--we declare a new DataFile object (and this is this new version1747

of the DataFile with the private properties), and then we try to set those private properties--1754

for example, we try to set the file name to index.html--and we try to run this new file called private.php,1759

what we can see is that we get an error: "Fatal error: Cannot access private property DataFile::$filename."1769

That shows how you are not able to set private properties using this regular accessor syntax.1775

And that is because they were declared private.1781

Let's get rid of these, and now, down here, we are going to try to output or to get the values of these private properties.1783

We are going to try to get the filename property; we are going to try 1793

to get the accessMode property--or the values of those properties--and then output them, just as we had done before.1795

Now, because they are private, we should not be able to do this.1802

So, when we run our script, we are going to get a new message that says "Fatal error: Cannot access private property DataFile::$filename."1803

And it is saying on line 38...so if we go back and look at line 38, we can see here--1814

this is where we tried to access this private object property from outside the class.1819

That shows how you cannot get private properties from outside the class, as well.1825

Now, the other thing that we have done is declared this open function...1832

Just temporarily, for illustrative purposes, we have declared this private, which means it is only accessible within the class definition.1838

For example, you can only access it within other object methods.1845

For example, right here--this would work OK.1852

Let's save it back to its original state.1863

So now, this is declared private.1865

Down here, when we try to call this private method, we are going to get an error, because it is going to say,1867

"You can't call that method; it is a private method, only accessible within the class."1871

When we refresh this page, "Fatal error: Call to private method DataFile::$open."1875

So again, this illustrates how that private access modifier on object properties and on object methods1883

affects your ability to access the properties and call those methods from outside a particular class.1891

So, now that we have created these properties as private, and we have said that you should keep your object properties private--1899

you want to protect them and make sure that they stay in an appropriate state--1907

well, sometimes you are going to need to access those properties.1913

You are going to need, for example, to...in this particular case, maybe we want to get the name of the particular file.1915

Well, PHP provides another magic method called __get.1921

And what that does is allows you to access these private properties.1926

And what it does is: any time...for example, let's say we have been using our new DataFile class that has the filename property declared as private.1932

And we want to set it outside...1956

Actually, we are using __get...we want to echo it.1958

When we tried to do this before, we got an error that says the filename is a private property.1969

However, if we define this magic method __get, any time PHP encounters you trying to access a private object property,1974

it is going to invoke this __get method that you can define, and it is going to allow you the ability1985

to provide access to those private property values, if you want.1989

And so, it gives you access to these private properties.1996

And this is the only way to access those private properties, assuming that you don't have any other public methods 1999

that allow you to access those properties, which we are going to see a little bit more of in a future slide.2005

For example, if we look at our new version of DataFile.php, we have declared this magic method __get.2011

And here, we output a statement that says that we are inside this __get method.2020

That is going to let us know when PHP is invoking this method, because what we are going to see in our code2026

is that we never actually call this method, __get, with some value.2030

It is done automatically by PHP; and that is how magic methods work.2040

This is going to let us know when __get is being called.2043

What our __get method does is takes the name of a property as its parameter.2047

And then, it allows you, because this function has access to private properties...it can use the $this variable2051

to access whatever property we want, that we pass into this __get magic method.2059

What happens is: any time you try to access a private property, for example, here--like the dash, greater than, filename,2067

essentially, what PHP is doing is calling our __get method that we defined.2083

And we are passing it the value filename; that is essentially what is happening behind the scenes.2093

In our __get method that we have defined, which takes one parameter, which is the name of a property we want to get,2098

what it does is takes that name, and then it just returns the value of that.2105

So, this is going to allow us to have access to private properties.2110

For example, in this get.php script, it is going to show that this is the same script that we had before, where we are trying to access private properties.2114

But they are going to work now, because we have defined this __get method that allows us to access inaccessible or private properties of an object.2123

So now, when we run this script (which is now called get.php), we can see a couple of things.2131

First of all, we can see that we are in this __get magic method, which is interesting, because we never actually call that __get method.2139

And again, PHP automatically calls that any time you try to access a private variable using this accessor syntax,2149

and that variable is private, and you have defined that __get method.2160

So again, this is a magic method, so it gets called automatically.2164

So, we can see that we are in the __get method twice: we are in it once when we try to get the filename 2167

(and now we are able to get the filename that we have set for this particular object),2171

and then, we are also able to get the access mode.2176

So, this __get magic method allows us access to private properties.2178

Well, there is an analog to this called __set, which is another magic method that works in the same way,2184

except it allows you to set the values of private properties which are considered inaccessible.2190

Normally, when we had our old version of the script (let's take a look at it...let's go to version 5),2199

when we tried to set private properties before, it works when they are public, but it doesn't work when they are private.2227

Well, this set method is going to allow us to change that.2237

What you do is define this __set method that is going to work the same way as...2240

Any time you try to set a method using the accessor syntax, for example (just .txt is the name of the file)--any time we try to do this,2244

if filename is private, any time PHP sees this accessor syntax going on, because it is a private variable,2265

it is going to go ahead and invoke this __set magic method.2272

The __set magic method, by definition, has two parameters that it takes.2277

One is name, and one is value; and you can set them to whatever name you want, but that is essentially what they represent.2283

And what it does is: name is the name of the property that you want to set.2291

So, in this case, when we try to access this up here, what we are going to be doing is calling $df-->__set.2297

We are going to be passing it filename, which is the name of the property we are going to set.2312

And then here, this is the value we are trying to set it to, so it also takes a value parameter.2317

This is essentially how this __set magic method works.2326

It takes the name of the object property you want to set and the value, and then it allows you to go ahead and set them.2332

And it allows you to define the way you want to do that.2338

And also, one thing to mention is that it will allow you, for example, to maybe perform some error checking.2341

Maybe you don't want to let a file called .txt be set for this particular file.2347

So, within your __set method, you can say, "If the value equals .txt, don't do it."2353

So, this allows you to have the control, again, over access to these private properties.2359

For example, if we go look at our new DataFile class, we still have all of our private object properties.2367

We have our __get magic method, and we have our __set magic method.2379

And again, it takes two values: the name of the property we want to set, and the value.2383

And in this case, any time this method is called (and it is going to get called automatically by PHP), we are saying,2387

"Whatever the name of the property is that we implicitly pass to this __set magic method,2395

we are going to set the value of this object's property that has that name to the value that we passed in."2402

So, as we saw in our example, in this case, __set would set the filename.2408

When we call this up here, and we try to run this code up here, we are going to be calling the __set method 2416

with filename as the property name, and then .txt as the value we are trying to set it to.2424

One other thing to note is that we have also included a statement here that shows when we actually are in the __set method.2433

And that is, again, to show how PHP implicitly calls it.2438

If we look at our file set.php, we declare a new DataFile instance.2441

We set it equal to a temporary file named tmp.txt, and we give it a w access modifier.2447

Now, we are going to try and set these private object properties (the filename and the access mode--in this case, to index.html and r).2453

What is going to happen is: because we have declared this __set magic method, we are going to be able to do that now.2461

It is going to provide us the ability to set those private properties.2469

When we go to run this new version, we are going to see two things.2472

It is going to say, "OK, it is in __set, and it is setting" and it says what property it is setting.2479

Here, it is going to be setting the filename; here, it is going to be setting the access mode.2485

Because these __set methods don't return anything, we are not outputting what it gets set to.2489

We are just saying that, when we are in this method, it is going to output and say, "This is the name of the value that we are trying to set."2493

So, in this particular case, it is going to set it equal to index.html and r.2507

And then, if we wanted to, we could echo these--let's just echo the filename, for example.2512

Because we have our __get magic method defined, we should be able to see that it outputs the new value that we set the filename object property to.2519

And we were able to do that because we had defined this __set method.2535

Now, one thing to note is that the __set method allows you to dynamically add properties to an object instance,2540

which often is undesirable--and in most cases, is.2549

For example, because we have this __set method, we could go ahead and add another property to our DataFile class.2553

Let's create an object property called fake, and I'll set it equal to fakeValue.2566

Now, because this __set method works, the other thing that these __get and __set magic methods do is:2575

not only does it allow access to private properties, but if you try to set a property that doesn't exist,2584

or get a property that doesn't exist, it also is going to call that __get or __set method,2592

and provide it, in this case, the name of the property you are trying to set, and then also, the value.2596

In this case, down here, if we echo fake, this is going to try to return the value of the property fake.2602

And it is going to allow that, because when we look at our code...for example, when we call __set first,2613

we are going to be able to say...2619

What this is going to do is create this new property fake and set it equal to the value we set it to.2622

And then, this is going to allow us, because we have set it, to access that value.2627

For example, if we try to create this new object property, fake, and then we try to output it,2632

and we run our file again, we can see that we are setting that fake variable to that setter method that is called.2645

And then, we are also able to access that object property.2651

So, in a sense, we have added a property to our object, and that is something that you are typically not going to want to do.2655

This __set method is going to be used in certain more advanced circumstances.2661

But I did want to show that to you, because you will see that used in code that is out there--2666

for example, in frameworks and different projects on the Web.2674

The alternative to using these __get and __set magic methods is to create your own public getter and setter methods.2680

And they are also ways to provide access to private properties.2688

For example, we can define a new data file class with private properties.2691

But now, for each property, we are going to define getters and setters.2699

We are going to define a public function (which means it is accessible to everybody) that says, "get filename."2702

And when it is called on this particular object, it is going to return the value of this private variable filename.2707

And the reason it can do that is because, within this function, you have access to the values of these private variables.2713

So, this way, we have provided a way to get the value of the private filename variable.2718

We provided a way to get the accessMode variable.2723

And as you can see, we create a separate method for each one.2726

That is one way to do it, and it is something you might see out there.2729

And typically, the nomenclature used for doing that is: you call the method get, starting with a lowercase g,2733

followed by the name of the variable you are trying to get.2742

And it uses upper CamelCase notation: so here, for example, Filename is capitalized; here, AccessMode--the first letters of each are capitalized.2745

Similarly, you can define set functions that typically are called set, followed by the name of the property you are trying to set.2754

And they take the value you want to set it to, and then within the function, all they do is:2760

they access that private variable and set it to the value you passed in.2764

As you can see, in this script, there is no __get or __set method.2769

So, theoretically, we shouldn't automatically be able to access those variables.2775

And in fact, in this new file gettersSetters.php, here we are just creating our DataFile, as we had been in our other scripts.2779

Let's say that we try to access filename.2790

Now, this is something that has been declared private.2798

And when we try to use this, PHP is going to look for that __get magic method.2800

If it doesn't find it, it is not going to allow you to access this; if it does find it, it will allow you to output that private property, if you want.2806

We haven't defined it in this class; so when we call this now, and try to run this new script, we can see that it can't access private property.2812

Let's go ahead and get rid of this line.2822

And then, what you can see down here is: we have made use of these getters and setters that we have created; they are these new methods.2824

So, instead of using the accessor syntax (dash, greater than, and then the name of the property),2831

we are using these public functions that we created in order to set these private variables.2840

We are going to set the filename to index.html and the access mode equal to r (which is different from the values that were set in the constructor).2844

And then, we are going to use these getters we defined--these public methods--to access those private variables, filename and accessMode.2851

So, when we go to output them, we should see that filename had been set to index.html (and therefore, it will get output),2859

and accessMode had been set to r, so it is going to get output.2865

So now, when we refresh our file, we can see that, in fact, that is what happens.2868

filename has been set to index.html, and accessMode has been set to r.2872

So, what you can see is that these setter methods that we have defined allow us to set private properties.2877

And then, these getters that we have defined allow us to get access to private properties, as well,2885

without using the __get and __set magic methods that you can provide, that PHP will call automatically for you.2890

Typically, you might use a combination of __get, __set, and any public setters and getters you define2903

to provide the ability to get access to an object's properties.2911

The way we are typically going to do in this course is: we are going to be using the __get method to provide access to private properties.2915

And instead of providing this __set method (because that allows you to add properties to an object,2922

which is not really typically a desired feature), for any private properties we want to be able to set,2927

we are going to define some public setter methods.2935

And so, that is what we are going to use in this course; and that is to set any private properties.2937

And I just want to mention that, in general, it is good practice to allow other code2943

to only be able to get and set private properties when it is necessary.2948

You don't want them to be able...for example, let's say you have a class with 10 different properties.2954

You could provide a setter method called setX, with X being the name of the property, that would take a value for all 10 of your properties.2963

But unless you really need the other code to be able to do that, you don't want to do that.2973

And again, that is that idea of data encapsulation, of protection--that you want to be able to have control over your data.2979

So, you don't really want people getting, or particularly setting, the data if they don't need to be.2986

And then also, you don't want them to be able to get the data as often,2993

because typically, with object-oriented programming, you want the object to be able to provide any functions it needs.2997

For example, when you call a get method on a function, you are basically saying, "Give me a property, and I am going to do something with it."3006

Well, one of the methodologies behind object-oriented programming is that the object should be able to do any functionality associated with it.3011

So, if you are getting that filename (for example) to do something with it, maybe you should define a method 3019

within your DataFile object (for example) that does whatever operation this other code may be trying to do.3024

For the homework challenge, I want you to create a Person class that has two private properties: firstName and lastName.3034

And then, provide a constructor that accepts no arguments, but it initializes both of these properties to the empty string.3043

Then, provide a destructor that simply just outputs a message that says, "Hey, I am in the destructor."3049

Provide a __toString method, which is a magic method that, when you use a Person object in a string context,3054

is just going to output the firstName and the lastName properties of the Person, separated by a space.3063

So, it is basically going to output their full name.3070

Create a __get magic method that allows you to access the private firstName and lastName properties of the Person class.3073

And then, provide a public setter method; so, instead of providing a __set method to be able to set both of these private properties,3084

provide public setter methods for each one (for example, one of them would be called setFirstName for the firstName property).3092

Then, create a script that instantiates a Person object.3103

Use these public setter methods that we just described to set the Person's firstName and lastName properties.3108

And then, using the accessor syntax, go ahead and output the value of both of those properties (the firstName and lastName) that you had set.3116

That is going to show you, first of all, how to use public setter methods.3123

Then, when you try to access it, it is going to show you that that setter method actually worked, assuming it had been implemented correctly.3128

And then, what this is going to show you is that, when you use this accessor syntax on private properties,3136

PHP is automatically going to call that __get method that we defined, that allows you to get access to those properties.3142

Then, I just want you to output the Person object as a string by just including it in double quotes--echo and then double quotes with the object.3148

And what that is going to do is convert it to a string, which means PHP is going to implicitly call that __toString method.3156

So, that full name should be output.3161

Then, what I want you to do is unset the Person object, using the unset construct in PHP, where you just provide it...3163

for example, it is a DataFile object called df, you just provide it the name of the variable.3173

What that is going to do is unset the variable and set it to null.3177

It is going to destroy the variable; that is going to implicitly call the destructor.3179

And that will allow you to see that destructor message.3184

Just verify that you are able to output the first and last name properties that you set, using the public setter methods, as you expect,3187

that the __toString method will actually output the person's full name,3196

and after you call this unset method, that the destructor actually gets called.3200

And you can see that by the message you have in your destructor being output on the screen.3205

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.3212

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application, 0005

incorporating what we learned in our last lesson about some new magic methods.0008

One of the things that we will do before we get into the magic methods is that we have made0014

all of our object properties and all of the classes in our web application private.0018

For our Customer, our Item, and our Department classes, we have made all of the variables that they have private.0023

Because they are private, and we need access to those variables, we are going to be defining the __get magic method for those classes,0030

as well as a couple of public setters to be able to set some of those private variables.0041

In addition, we have added the to_string method to our Item and Department classes0046

(which, as we learned about, is a method of--when you use an object variable within a string context, 0051

it is your way of deciding how you want the object to look represented as a string).0056

Then, we are also going to create a new class called DataFile, which is similar to the one we used in our last lecture,0062

which is going to encapsulate all of our file input/output operations.0069

So again, all of the properties for our Customer, Item, and Department classes were made private.0077

And because we need to access these different properties, for example, when we are outputting information about an item on Item.php,0083

we need to be able to have access to them, so we have added the magic method __get to each of these.0093

And what we have done in that __get method is provided access to those properties.0099

For example, it just returns the value of whatever property you are trying to access by this name parameter, which we will see in a second.0104

And then also, to our Item class, we have added two public setter methods 0121

for the item ID and image file extension private properties, so that they can be set from outside the class.0125

And here, we are not using the __set method--again, because that allows the creation of additional object properties that we don't want.0133

And we are only providing setter methods for item ID and image file extension, 0145

because we only want to provide access for users to be able to set these particular properties.0149

We don't need them to be able to set description, price, and name, because those are set in the constructor,0155

and that falls under the category of data encapsulation, which we have talked a little bit about,0161

which the object-oriented concept of having the object control all of the information about its data, as much as possible.0166

If we look at our new classes (let's blow this up a little bit)--for example, our Customer class--0175

one thing we notice, first, is that in our documentation here, we can see a list of all of the variables for our Customer class.0187

And it describes each of them, and says that firstName represents the first name of the customer; its access is public.0196

Well, in our new version, we don't have those variables; and that is because they have been declared as private.0202

Because they are private...this documentation is meant for people that are going to be using your class.0207

Because they don't have access to those variables directly, it doesn't list them on here.0214

So, that is one thing to notice.0218

Then also, what you can see is...actually, let's look at the source code of the file.0221

You can see that we have declared each of the object properties as private.0228

And then, we have created our __get magic method; and all it does is returns the value of whatever private property we are trying to get.0235

Now, we have also done the same thing for Department, which, as you can see, 0246

no longer lists the department variables, because they are no longer public; they are all private.0250

And we have the same __get magic method that just returns the value of the private property which allows access to it.0257

And item does the same thing, so we have essentially replicated this in three different spots.0264

And we have done so for each class; and that is to make all of the variables private, and then also to provide getters to access them.0271

Now, in addition, for our Item class--for example, on our addItem page in our admin website--0278

when we initially create an Item object to insert into the database, we don't know its item ID, and we don't know its image file extension yet.0285

For example, when we call the constructor, we don't have values for item ID and image file extension, so we set them equal to null.0292

So, we need ways to be able to set these now-private properties after the object is created.0299

So, we have created two public setter methods, setImageFileExt and setItemID.0305

And if we go and look at these, it simply takes the value that we want to set 0313

for the image file extension, and then sets the private property equal to that value.0316

And the same thing for the setItemID: it takes an item ID as its parameter, and then sets the private itemID object property to that value.0322

If we go and look at our insertItem function, an insertItem function is what is called 0335

from our addItem.php page in our admin site, that is used to create a new item.0347

And we pass it an item object, but it is an incomplete item object.0352

The item ID is missing, and the image file extension is missing.0356

Here you can see that what we do is: we use this new public setter method that we have defined 0359

to set the item ID to the one that we get from our lastAdded file.0366

Here is an example of using that new setter method for the same thing.0374

We get our image file extension from the name of the image that was uploaded, 0379

and then we can set that new item that we have created, using this new setter method that we have, setImageFileExt.0383

And this is opposed to in our last version of this, where we just explicitly accessed the properties, using this accessor,0391

because they were public properties, so we could just directly set image file extension and item ID.0399

Now that these properties are not public (they are private) we can't do that anymore.0404

The other thing that we have done is implemented the __toString magic method for our Item and Department classes.0412

What we have done is: previously, we have had functions createDeptDataString and createItemDataString.0421

And those, we have been using to take an Item object, take a Department object, 0429

and combine them into a delimited string that we store in our items.txt file and our departments.txt file.0433

These functions have been stand-alone functions in our file library of functions that we have had.0440

Well, now it kind of, in a way, makes sense to move them into the object methods.0447

For example, because a Department object knows all of the information about an object,0454

why not have a method in it that is able to create a string that represents that?0459

Well, to be able to do that, and to illustrate the use of the __toString method, we are going to implement the __toString method for both those classes.0463

And it is going to perform the same functionality that these two createDataString methods provided.0473

We are eliminating those from fileLIB.php, and then we are creating __toString methods in our Item and Department classes.0478

For example, if we look at our older version, we had createDeptDataString.0490

And what that would do is: we would simply pass it a department object.0496

And then, it would go through and build up this string that we store in departments.txt, which is delimited by vertical pipes.0499

And then, the items in the department are separated by commas.0508

That just builds up this Department string, the same way our Item data string builds up a string that represents the item.0514

And again, we pass it an Item object.0522

We are passing it an Item object to create a string from that Item object; 0525

why not include that in the Item object already, as a defined method?--because that Item object 0529

already has access to all the information that we are already passing in.0536

We are going to make use of the __toString method, in this case.0539

If we look at our new Item class, for example, you can see we have a __toString method.0543

And let's just look at the source code.0551

And in our __toString method, you can see, it pretty much does the same exact thing as we had in our other version,0558

except that, whereas in createItemDataString, because we passed it a variable that is an Item object,0565

we use that variable name to access the different property values of that object;0573

well, now we have defined __toString within the object class; so this is within our Item class definition.0581

Now, to access these properties, we use the $this variable to access them, because if you notice,0594

we don't have a variable to pass in, because we don't need to pass it an item variable, because via this $this variable,0599

this object method will have access to the properties in the class.0606

Here, we perform the same functionality, except we use it as a __toString method.0610

The same thing happens in our Department class: we have a __toString method, and it performs the same functionality 0616

as in our createDeptDataString method, except it is now using the $this variable 0622

(as opposed to the departments variable) in order to access these different properties.0629

And of course, because these are private properties--private properties are accessible within class methods.0635

And so, we can use the $this variable to access them.0646

If we take a look at how some of these are used--if we look at insertItem in the new version,0650

we can see that one of the things that we do is: when we insert a new item into our database,0666

we create that item data string and insert it into the items file.0674

In our last version, the way we did that was (this is within the insertItem method): we would open the items data file,0678

and then we would call this createItemDataString method, append a new line to it, and then write it to the file.0690

Well, now what we are doing: because we already have this __toString magic method built into our class now,0696

now we can simply create an item string that just includes the variable that represents the Item object within double quotes,0702

which means it is going to be used in a string context, which means that __toString method is going to be automatically called by PHP.0711

So, that __toString method that we have now defined that creates that item data string is going to be generated.0717

We append a new line to it, and then we add it to our file.0722

And we are going to talk in a minute about the new method we are using for doing that.0725

Similarly, in our updateDept method, when we update a department, we add lines to the Department file,0730

or update lines in the Department file, with new items added to a particular department.0738

And let's go to the previous version: the way we previously did that was: we would call createDeptDataString,0746

pass it an object, append a new line to it...and then, we would loop over all of the lines we had extracted from the file 0755

and add these department data strings back to the file.0765

Well, in our new version, we don't need to do that anymore.0771

Let's see, where is...0776

And what we can do instead is: now, instead of calling createDeptDataString, 0781

we just enclose the variable that represents our Department object within double quotes and append a new line to it.0786

And now, that is going to implicitly (again) call the __toString method that we created for the department.0795

It is going to create that department data string, and then we are going to be able to go ahead and add it to our particular file.0799

Probably one of the biggest things that we did in this new version of the web application is created a new class called DataFile.0808

And its purpose was to encapsulate all of the file operations that we have been doing,0815

because in all of our different methods that we have had...and we introduced this concept a little in our lecture on magic methods,0822

where we introduced the DataFile class during the lecture.0829

If we look at, for example, our last version of the web application: we have all of these functions within our file library,0834

most of which access a file; they open a file up; they read from it; the open a file up; they write to it; they close the file; and so forth.0841

So, there are a lot of similar operations going on here.0852

We even have three separate functions: for example, openDeptsDataFile, openItemsDataFile, openLastAddedFile.0854

And all of these different functions (let's look at the source code) essentially perform the same thing.0862

If we look at the code for openDeptsDataFile, and we look at the code for openItemsDataFile, the code looks almost exactly the same.0880

So, our rule is: if we have code that we are reusing over and over--the same code--why not put it in one spot and be able to reuse it?0889

By putting this code in a single class, we can take advantage of reusing that code.0898

That is going to eliminate making mistakes, because now, let's say, any time we want to change how this operation works,0906

we have to change it...for example, in this case, we might have to change it in three different spots,0912

because we have three different methods that are used to open files.0915

Now, we can put this open method within our new DataFile class.0918

And any time we want to change how we open a file, we can just do it in that one spot.0925

So, what we are essentially going to be doing is: for every file that we are going to be accessing or opening,0930

we are going to be creating a DataFile object that is going to represent access to that particular file.0934

In our new version, we are going to be getting rid of all three of these openDeptsDataFile methods.0940

And what that is going to do is: for example, one of the things that we do is: they all use the fopen method.0947

They all also output an error message and return false, for example, if there is an error opening the file.0954

Now, we can put that same functionality into one place, so we don't have to replicate this in multiple spots.0961

The other thing is: for example, if we go to our old getItem function, we have our openItemsDataFile,0971

which we just discussed as our way of opening a file.0978

Then, we manually loop over all of the lines in the file, looking for...0981

Actually, let's look at the itemsExist one; that might be a better example.0986

We manually loop over all of the items in the file, using this feof method and fgets method to try and find a particular item in a file.0989

Well, for example, if we look at the deptExists file, we are going to see that it looks very similar.0998

What we are going to do is put this file access, this feof call and this fgets call, all into this DataFile class that we are going to create.1007

And we are going to create a method, for example, called nextLine, that is going to allow us to read the next line from a particular file.1016

So again, this is taking code that we have used in multiple spots, and we are going to put it in one class.1023

Let's go and take a look at this new class that we have created, DataFile.1029

First, it has three different private properties: one is accessMode, one is fileHandle, and one is filename.1040

accessMode and filename are the name of the file that this object is going to represent, 1047

because this object is going to allow us to perform operations on a file.1052

filename is going to be what file it is going to be performing the operations on.1055

accessMode is going to be how we are going to be opening that file.1059

Are we going to open it in append mode? Are we going to open it in overwrite mode? Are we just going to open it for reading?1062

And we can set both of these; our constructor is going to take both filename and accessMode, so we can set them.1068

And then, we also have a fileHandle property, which is used internally within the class.1075

It is not accessible outside of this DataFile class.1080

And so, what it is going to do is: for example, the way you use a DataFile object (let's go to the slide for this)1086

that we have created is: you instantiate the object; you provide it with a filename and an accessMode;1097

then you call the open method that is provided by this class.1102

You perform some operations on it--such as, for example, getting the next line.1108

We will also see that there is an appendLine method that we have created.1111

And then, when you are done, you call the close method that is provided.1114

If we go and look, for example, we can see that there is a close function that is provided, which closes the connection to a file.1118

Let's see...there is an open method that allows you to open a file.1131

That encapsulates all of that code that we saw before for opening a particular file.1136

And then, we have other methods, such as...here we have a method appendLine, which is going to allow us to append a line to a file.1141

We have a function getLine, which is going to allow us to read the next line from a file,1150

and then a function getLines, which is going to allow us to pull an array containing all of the lines in the particular file.1155

We have this private fileHandle that gets created by our open method.1166

If we look down at the open method, we can hopefully see (I don't know why I called it and it's not working on this one)1171

that we have an fopen method that gets called within this open function.1180

And what it does is: it sets a private fileHandle object property equal to the fileHandle generated by fopen.1184

And fopen is just going to be called on the file name that we have set for our particular file that this object represents.1192

And we are going to open it in the access mode specified.1201

And again, both of those were able to be specified in our constructor.1204

Our constructor takes the filename and the accessMode and does a little bit of error checking.1208

It tests to make sure that the filename is a valid filename, and if so, it sets filename equal to that.1213

Otherwise, it sets it equal to null.1221

It checks to make sure that accessMode isn't empty, and it goes ahead and sets it equal to the empty string if it is empty; 1223

otherwise, it sets it equal to the value passed in.1231

And then, as part of our always initializing all of our object variables in our constructor, we initialize the fileHandle equal to null.1233

And that is because, when the user calls the open method, that is going to allow them the ability to set that private fileHandle variable.1240

And that is going to be created by the fopen method.1248

Let's take a look at this class in action.1254

If we look at our getItem function, for example...1257

And this DataFile class is used in all of our functions within our file library that have access to a file.1262

And we don't have time to go over all of the examples of it.1270

They are documented in the change log for this web application.1272

But we are going to go over a couple of the different examples, so you can see how this new DataFile class is used.1276

For example, in our getItem class, where we are trying to load information about a particular Item 1281

from our items text file, based on an Item's ID; the first thing we do is create a new DataFile object.1286

The name of the file is going to be the name of this constant ITEMS_DATA_FILE, 1295

which is something that we set in our config file, which ends up being a path to items.txt.1300

We are going to open it; we are going to set that this file, when it gets opened, will be opened in read mode.1306

Then, what we do is perform the public method open on this file.1312

And open returns true or false, based on whether or not the function is able to successfully open a connection 1317

to the file specified by the filename parameter of the DataFile constructor.1324

And so, what this is also going to do is: as we had said, the open method is going to set that fileHandle object property of our DataFile class.1331

So now, when we run other operations on this DataFile class, they will be able to access that file.1340

For example, the thing that we do in this particular function is: we loop over each of the lines in the file,1347

reading a line and extracting information to see if it matches the item ID that we are looking for.1353

So here, after we have opened the file, and now we have a valid file handle, 1360

we are going to be calling this nextLine function that we have created in our DataFile class.1365

Let's open this up in another window.1374

And if we look at our nextLine class, what it does is says, "If it is at the end of the file, return false; there are no more lines to read."1380

If it is not, it says to go ahead and get the next line of the file.1388

It uses the fgets method, and it operates on this private variable fileHandle that was set by the open method.1392

And it accesses it by the $this variable, because it is a private method.1400

And any time you access an object property within an object method, you use the $this variable.1405

What we do here is: we loop over while this still returns the line, because what is going to happen is:1416

nextLine is going to return false when it reaches the end of the file.1422

Then, it is going to kick out of the loop.1424

While it is still returning the next line, we are going to perform the same functionality as it does before.1425

We are going to be pulling out the first data field from a particular line, checking to see if it is the same item ID we are looking for.1430

If it is, then we are going to be building up an item object using our buildItemObject function.1437

And then, that is what eventually gets returned.1442

Down here, we finish our operations by calling this close method on the itemsDataFile on our DataFile object.1444

And if we look at the close method, we can see that what it does is calls fclose on the fileHandle that we have that is open,1453

assuming that the fileHandle has not already been set equal to null.1462

One of the things that we do is: when we close the fileHandle for this particular object 1466

(that is a property of this particular object), we also set it equal to null.1473

And that is also for use in our destructor, which we created in this class, which we are going to talk about in a second.1478

And we talked a little bit about that in the last lecture.1482

The close method just checks to see if the fileHandle is already null.1485

If it is, it just returns true, because the file is closed.1488

Otherwise, it goes ahead and closes the file, and then it will output an error, for example, if there is an error in closing the particular file.1491

That is how using this new DataFile class works.1500

You instantiate an instance of it with a file name and an access mode.1505

You call the open method on it to open a connection to the file that you specified in the constructor.1509

You run operations on it; for example, in this case we are performing a read operation, which is readNextLine.1516

And then, you call the close method on it.1522

Another method that this class provides is called getLines, which returns an indexed array1525

where each value in that indexed array is a line of the particular file.1536

For example, we use this with our getDepartments file; we read all the lines from the departments file.1542

To use this in our getDepartments function, we create a new file that says it is going to represent the departments data file.1548

When we eventually open it, we are going to open it in read mode.1559

We open the file, and then we call this getLines method on it.1561

And it is going to pull an array of all the lines in that data file, represented by this departments.txt file, and put it in this lines variable.1565

And then, this function still performs the same operations as it did before.1575

It goes through and builds a Department object for each data line that it gets from that file.1579

And down here, you can see we finished the operation with the close method.1590

The one other method that we provide in this class is the appendLine method.1594

What it does is: it takes a string that we pass to it, and it appends it to the file that this DataFile object represents.1607

One thing it does is tests to see if the line...because it is appending a line, lines have new line characters at the end;1617

and it tests to see that the line that you have passed in, when you call this method, has a new line.1622

If it doesn't have a new line, it adds one to it.1627

And then, after it does that, it goes ahead and calls the fwrite method, 1629

which operates on the private fileHandle object property, and then just writes that line to the file.1633

And then, it returns true or false of whether that was successful or not.1641

We use this in our insertItem function when we insert a line in our items.txt file.1644

Here, in our insertItem function, we can see that we created a new DataFile object.1653

We set the items data file to open in append mode; we opened the file; and then, we use this appendLine method to append the new line to the file.1659

And then, we call our itemsDataFile close method to finish the process.1671

That is how that DataFile class that we have had works.1676

It takes all of these common operations that we have had spread out through different parts of the code,1679

and encapsulates them in a single class, so that we can reuse it in multiple spots.1685

Now, one other thing to note is that our DataFile class--we have actually added a destructor to it--1691

the __destruct method, which is a magic method in PHP, as we learned.1697

And we use our __destruct method to make sure that, when this object is no longer being used, it closes any open files.1702

Let's say, for example, what we had said--that the typical procedure for using a DataFile object is that you instantiate it;1708

you call the open method; you perform some operations on it (like appendLine); and then you call close.1715

Well, let's say that somebody that is using our object doesn't call this close method.1720

Well, when this script ends, or when that itemsDataFile variable gets set to null, the destructor is going to be called.1724

And the destructor--what it is going to do is test to see if the file has already been closed.1730

And it does that by testing to see if the file handle is null.1736

And if it isn't null, then it goes ahead and runs its own object method, close, which as we saw,1739

calls fclose on the file and then sets the fileHandle equal to null, which is how the destructor knows if a file has already been closed or not.1747

Our destructor just makes sure that the file was closed, so that we don't have a file left open.1757

And so, that is an example of using a destructor; and it is similar to what we used in our last lecture.1766

For today's homework challenge, I would really like you to just study the DataFile class, as it is somewhat of a complex class.1777

We are really starting to get more into our object-oriented programming.1784

We have constructors and destructors; we have magic methods; we are using private object properties.1787

So, this DataFile class incorporates a lot of that different stuff.1799

So, make sure you can understand the class and how it works, and specifically understand how it is being used within our fileLIB functions,1802

because a lot of functions within that fileLIB (and again, they are spelled out in the change log)1812

are going to make use of this DataFile object, because they are performing a lot of file operations.1821

So, this is going to be used in multiple spots.1825

And then also, just be sure to make sure you understand how the destructor works,1827

and how that ensures that when a DataFile object is destroyed, that it makes sure that any files it had open were closed beforehand,1833

which is important; you always want to close your file resources.1842

And so, that is a way of keeping things clean, to make sure that if your user didn't explicitly call (for example) the close method1848

on a DataFile object, that it will go ahead and still be closed anyway.1861

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1868

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing discussing the topic of classes versus objects.0004

We are going to have a review of what classes and objects are, and the differences between the two,0011

because that is going to become important when we learn about what are known as static properties and static methods.0016

So far, what we have been working with (as you will find out) have been known as instance properties and instance methods.0023

They are properties of a class and methods of a class that relate to a specific instance of that class.0029

We are going to learn about something a little different; it is on more of a class level.0035

We are going to talk about an operator called the scope resolution operator, 0040

which is going to allow us to access these static properties and methods that we are going to learn about.0043

And then, we are also going to learn about constants in classes.0047

We know about being able to define constants in our regular PHP files; we are going to learn about how to define them at the class level.0050

A class, as we know, is essentially a user-defined data type.0061

And when you create an object, what you are doing is creating an instance of that class.0065

You are instantiating a copy of that class, and you are filling in the values for the properties of it.0069

Essentially, what you have between a class and objects is a one-to-many relationship.0077

You have one class definition, and you can have as many different object instances of that class as you need.0081

The class provides the template, and the objects are the realization of that class.0088

But in the case of each instance--each instance is essentially (as we had mentioned) its own version of that class.0094

So, they have their own version of all of the properties.0112

For example, we have learned about object properties.0115

Object properties defined in a class definition get initialized and set when you create or instantiate an object.0116

Those properties are specific to that particular instance, so each instance of an object has its own copy.0119

For example, if a Person object had the firstName property, each Person object you create 0123

would have its own copy of the firstName property, and it would be specific to that instance.0130

And so, for that reason (we haven't specifically called them that, but the distinction is going to become clear today), those are known as instance properties.0134

So, all the properties that we have been dealing with so far with our classes are known as instance properties.0141

They are properties that are specific to each instance of a class.0146

Each time you instantiate a class as an object, it gets its own version of those properties; and they will be referred to as instance properties.0150

Static properties are what we are going to talk about today.0164

Static properties are, in a way, like class properties; they are properties whose values are shared between all of the instances of a particular class.0167

So, whereas in your class definition--let's say, in our Person class--we have a firstName property;0181

well, that is an instance variable, if we define it as we have been...0188

And that means that it is an instance property, meaning that each instance of that class has its own copy of that property.0192

However, a static property is per class, meaning that there is one property defined in that class definition0202

that all of the different instances have access to, but it is not like they get their own individual copy.0209

So, if one instance of a class updates this static property of the class, it affects all of the other instances, in that they all read that same value.0215

The way you declare a static property in a class definition is using the static keyword.0227

Whereas before, we had just been saying public numPeople, and that would be our property definition;0233

now, we are added the static keyword: we are saying public static numPeople, and we are giving it an additional value of 0.0239

What this statement says is that we are declaring a public property that is a static property.0245

It is going to be called numPeople, and its initial value is 0.0250

And this would be contained within a class definition, just with all your other properties.0255

One other thing to note about static properties is: because they are not specific to an instance of a class--0260

they relate to the entire class, or all of the different instances of that class--0267

you don't have to have an instantiated object in order to access them.0273

Normally, for example, let's say we have a Person class, and it had a property firstName.0277

Well, to access that firstName property, we would write something like this.0290

And what this is: it is a reference to this instance of the Person object that was created.0298

Well, that is why it is called an instance variable, because this copy of firstName is specific to this a variable right here.0304

Well, because static properties aren't specific to a particular instance, you don't reference them using an object variable.0315

And we are going to see about that in the next slide--about how you actually access them.0323

What PHP provides is the scope resolution operator, which is two colons, one right after the other.0328

And that is how you access static properties.0334

For example, if we had a Person class where we defined a static property called numPeople0337

(just as in the last slide, public static numPeople equals 0), well, in order to access the value of that static variable outside of the class,0342

the way you access it is: you write the name of the class, followed by the scope resolution operator,0353

followed by the name of the variable--including the dollar sign.0359

And so, outside of a class, this would be how you reference numPeople.0364

And the reason you can access it: it is essentially the same thing as a class property,0369

because numPeople is a property of this Person class, because there is only one version of it.0375

There is not a version for each instance of the Person class.0378

And you can do that for public static properties.0382

In addition, if you are trying to access a static property from within a class method 0385

(for example, if you have a class method defined within the Person class, 0390

and you want to access the static property), you do so using this keyword self.0394

If this was, for example, a function or a method within a class definition, in order to access the numPeople static property of this class,0400

of this object, you would say self, and then you would have two colons, followed by the variable name.0411

And again, you include the dollar sign, which is a little different, because when we access instance variables,0416

and we use this arrow operator, and if we had a property called numPeople, we access it like this, without the dollar sign.0425

So, that is one definite distinction between accessing static properties versus instance properties.0436

And then, another thing to note is: outside of a class, you can't access a static property using the arrow operator.0445

So, for example, if we had this numPeople static property defined in a Person class,0452

we would not be able to access it using this arrow syntax.0459

Assuming a was an instance of a Person object, we couldn't use this arrow operator in order to be able to access this numPeople static property.0462

The way you do it is: you have to have the name of the class with the scope resolution operator.0474

Let's take a look at a basic example of static properties in action.0477

We have this Person class that we have defined.0484

It has two private instance properties, and these are firstName and lastName.0487

And they are particular to every instance of the Person class that gets instantiated.0490

So, every Person object that is created gets their own copy of these.0495

We have a constructor that takes two parameters: one is the firstName and the lastName that you are going to set for the Person.0498

Here, we set these instance properties.0504

And then, we are just also outputting a message and a constructor, just to say we are creating a Person (firstName and lastName).0510

Now, up here, what we have is a static variable.0515

You can see here, with the keyword static, we say public static; we are calling the static property for this Person class description.0518

And it is a description of the class; it says, "This class represents a person."0526

It kind of makes sense that, for any Person class that you have out there, if you want to get a description of it,0530

they all might have the same description: "This represents a person."0535

So, this may not be the most practical example, but it is used to demonstrate the use of a static property.0539

I'll show a little more practical example in a couple of examples.0546

If we look at a script called staticProperties.php, we have an include statement that includes that Person class that we just looked at.0553

And then, what we have (let me bring this down to another line) is just a message that says, 0562

"I am outputting this static description property of the Person class."0569

And the way we access that is by the name of the class, the scope resolution operator (which is two colons),0578

followed by the name of the static property, including the dollar sign.0585

When we echo here, we are saying, "The value of Person::description equals" and then we are outputting it using this concatenation operation.0591

If we load this script up, and we take a look at staticProperties.php, we can see (let me blow it up a little bit):0601

Person::description--the value of it equals, "This class represents a person."0610

And if we go back and look at our Person class, we can see that that is the value that we had assigned to this static property.0616

That is how, outside of a class, you access a static property.0625

You use the class name, the resolution operator, and then the name of the property.0629

We had also talked about being able to access it from within a class.0635

So now, we have the same class here, except we have added what we are going to call (and we are going to learn about it in a minute) an instance method.0639

Up to this point, we have just been referring to it as an object method called getDescription.0651

And all it does is: it just returns the value of this class's static property description.0655

And as we mentioned in the slide, when we are trying to access a static property from within an object method, you do it using the self keyword.0662

When we are outside, we use the Person keyword--the name of the class.0674

You actually can do that within the class, but typically, what you do is use the self keyword,0677

because self means, "The class I am referring to is the same class of this object instance," which would be a Person class.0682

"And I want to get the description property."0690

So, what we have here is: we go ahead and include this new Person class definition and create two new people, Joe Smith and Jane Jones.0693

And then, what we do is: we are calling the getDescription instance method.0704

It is an object method; we are going to learn about static methods in a little bit, but for now, it's just a regular method like we have been using.0710

And what that is going to do is: as we saw, it is going to return the value of the static variable description.0716

So here, we are outputting the description static property for person1 and person2.0722

What we will see is that they are the same property.0730

And then, what we are going to do is change the property, using the syntax for accessing a static variable outside of a class,0732

where you use the class name and the scope resolution operator.0740

We are going to set the static variable description for Person equal to this new description: "No description available."0743

Then, what we are going to do is call this getDescription method on each of these Person objects.0749

And what we are going to see is that it is updated for both of them.0754

And so, in this example, we learned about how to access a static property from within a class method, or an object method.0757

And then, it also demonstrates how it is that one static property is for all of the different instances of a class.0765

When we call getDescription on this person1 and person2 object, and it returns that static variable,0772

they are both going to have that same value that they returned it to.0779

You can't have a separate value for the static property description for each instance of a class.0781

It is the same for all the classes of that type.0791

So, if we go and look at the script in our browser, insideClass.php, we can see "Create two Person instances," and there is some output from our constructor.0794

We created a Person Joe Smith, and Jane Jones.0808

And then, we can see that, when we first try to output the static property, which is before we changed it0811

(it was immediately after we created these Person objects, so for example, we instantiate the Person objects,0817

and then we immediately output the static variable description and the static default value for that variable,0823

"This class represents a person), it outputs "This class represents a person."0830

Now, when we go back and look at insideClass after we have changed it to "No description available,"0836

when we go back and run that same getDescription method that is going to return the value of the static variable description,0840

both objects are going to return that same string, "No description available."0847

And we can see, the second time we call it: they both output "No description available."0853

Somewhat of a more useful example of using an instance property is an instance counter, sometimes called a reference counter.0860

It is keeping track of the number of instances that you have of a particular class.0868

For example, each time you create a Person object, if you have a Person constructor, that constructor is going to get called.0873

What you can do is increment this; for example, here we have a static variable for the Person class called numPeople.0880

And this variable is the same for all instances of the Person class.0887

So, every time in our constructor, what we do is increment it by 1.0892

Every time we create a new Person object, we are incrementing this static variable numPeople by 1.0897

So, any time outside the class that we reference this static variable Person::numPeople, and we see what this value is,0901

it is going to equal the number of times we have run this constructor.0909

And it is going to be the same across all different classes, so when we increment numPeople here,0912

it doesn't just do it for any particular instance of this class; it does it for all of the Person classes.0916

We just changed our constructor a little bit to increment this counter variable called numPeople.0924

And then, the other thing that we can do is that we can create a destructor that, when the destructor is run--0931

when the object is destroyed--it decrements the numPeople static variable.0937

So, every time we create a Person object, the counter is going to go up by 1.0941

Every time we get rid of it, the counter is going to go down by 1.0944

We have a script here where we defined three different instances of a Person object that all have their own firstName and lastName instance properties.0948

But they all share the same numPeople static property.0961

And then, we have a statement here that just outputs, after we have created all these, a statement that says,0966

"The current number of Person instances is" and then we access that static variable Person, numPeople.0971

In this case, it is going to say 3, because we have created 3 Person objects.0978

The constructor is called 3 times, and for that case, it has been incremented 3 times.0982

Then, what we are going to do is get rid of one of the Person objects; we are going to set it equal to null.0988

That is going to implicitly call the destructor, which is going to decrement it by 1.0992

So now, it is going to say "The current number of Person instances" equals 2, when we again try to reference Person, numPeople.0996

If we go and look at this script in the browser, we can see an outline of what happens.1003

Before we even created any of the objects, I had an output statement that output that static variable for Person, numPeople.1014

Even for a class, even if you haven't instantiated an object of the class Person, you can still access its static properties,1023

because they are specific to the class, not to a particular instance.1030

If we go back and look at the code, I missed mentioning this line here, where before we have even created any Person objects,1035

we are still able to access this numPeople static property of the Person class,1043

because it is on a class level, rather than an instance level.1050

And if we can see, we had initialized it to 0; so when we first run this output, it is going to say "The current number of Person instances is 0."1054

Then, we say we are creating three Person instances, and it shows us the three people we created.1064

When we output, now, the value of that static property numPeople, it is going to say 3.1069

We destroy a Person instance--we get rid of the first one, Joe Smith.1075

And then, when we output the static value again, numPeople, we can say the current number of instances is 2.1079

And so, it shows that it was able to decrement.1085

And down here, you can see: these destroying messages come from our destructor.1087

And the reason they are down here is because we know, when a script ends, PHP destroys all of the objects,1092

or calls a destructor on any objects that were still being used.1098

And so, since these objects were in use, their destructors get called automatically.1102

So, even though we didn't specifically call them, that is why they show up here at the bottom.1106

And so, that is somewhat of a more practical example of how you might use a static variable 1110

to keep track of, for example, the number of instances of a particular class.1116

And the reason you can do that is because it is the same for all of the different instances,1121

and when each one updates that static variable, all of the other ones know about it.1125

Now, we are going to talk about something called static methods, which I hinted at a little bit.1132

And it is essentially the analog of...where static properties are to instance properties, static methods are to instance methods.1136

And instance methods we haven't talked about, but what we have been declaring so far and defining in our class definitions have been instance methods.1145

They are methods that you call using an instance of an object.1153

For example, if we have an object a, and we wanted to say get name, this is an example of an instance method.1157

It works on an instance of a particular object.1171

It is going to have access to the instance properties of this particular instance, whatever class it may be.1174

And you use the arrow operator to get access to it, because it is specific to an instance of a class.1181

A static method, on the other hand, is not specific to an instance of a class.1188

And we are going to see that you access it using the scope resolution operator, as well.1193

The way you declare a static method is just like you do any other method in a class, except you include the static keyword.1199

And because static methods are not associated with a particular instance of a class, they can't access the $this variable within their definitions.1207

Now, this should make sense, because if you remember, the $this variable, when we use it within an object's...1218

what I want to refer to as instance methods, $this refers to this particular instance of an object.1226

Because a static method doesn't relate to an instance, it doesn't know about this.1233

It doesn't know about any particular object; it just knows about the class definition as a whole.1239

So, you can't access this within static methods, or you will get an error.1244

And as mentioned, the non-static methods, which is what we have been using up until now, are called instance methods.1249

And static methods are called using the scope resolution operator, just as we did with the static properties; we are going to see that in a second.1255

Outside of the class, you preface it with the class name.1264

For example, if getName was a static public method, we would call it like this from outside the class.1266

Within a class method, we would call it using the self keyword.1280

And again, note that we are using this scope resolution operator, as opposed to the arrow operator,1292

because we are not accessing a particular instance of a class.1297

Let's take a look at...I created this class called Integer that is sort of an object that wraps an integer value.1301

It has one private instance property that is called intVal, and it just represents an integer.1310

So, when we call our constructor, we pass it an integer (1, 2, 3, whatever), and then our constructor sets intVal equal to that integer.1319

We have an object method, or an instance method, called add, in which we can pass it an integer as a parameter.1327

And what it is going to do is access whatever particular instance we are calling it on (this instance)--1337

it is going to access its current int value, add it to whatever you pass in, and then return it.1344

If we look at our code, here we are creating an Integer instance, just as we do normally, using the new operator.1351

We are passing it that we want to set that class equal to (in this case, 1).1365

And then, we are adding 1 to it; and we are saying, "The sum of 1 and an integer with the value 1 equals..."1370

and then we are calling the addInstance method and passing it 1.1376

So, we are saying, "Add 1 to our current integer," which is already 1, so it is going to output 2.1380

Here, you can see: because this is an instance method, it uses this arrow (or dash, greater than) operator to access that instance method.1385

And it does so on a variable that has been set to a new instance, or to an instance of the Integer class.1395

Now, on the other hand, we could define a static method in this class--a static keyword called integers.1403

We simply pass it two integers, and it just returns the addition of them.1410

So, it does the function for us; but we don't actually need to access any object properties.1414

We don't need to access any instance properties, whereas up here, because this was an object method1420

and we wanted to add something, we accessed what the current integer value 1425

of this Integer object was, and then added to the value that was passed in.1433

Now, this is like a stand-alone function, but within the context of a class.1437

So now, if you want to add 1+1, instead we could access that static method addIntegers, and pass it the parameters 1 and 1.1442

And the way we call it is by prefacing it with the name of the class and the scope resolution operator.1451

This is saying, "Call the addIntegers static method defined in the Integer class, and pass it the parameters 1 and 1."1459

And it is going to return the addition of those.1467

So, when we view our script, we are going to see the sum of 1 and our Integer object that has int value equals 2.1468

The Integer value equal to 1 is going to equal 2.1483

And then, when we call the static method, the sum of 1 and 1 equals 2.1485

So, in this case, we haven't acted on an instance.1489

Now, one thing to note is that I mentioned that, just like with static properties, you can access static methods within an object, as well.1492

And so, in this case, we actually could do this.1504

If we wanted to, we could call this addIntegers method from within our add function, and have that do all the work.1508

It doesn't really make sense, but this is just an example to show how you would access a static method within another class method.1517

Use the self keyword, followed by the scope resolution operator, then the name of the method.1525

And then, in this case, we would pass it 2 values, because it is a function that takes 2 integers.1533

In this case, we are going to pass it the integer value of this particular instance of the object.1538

And then, we are going to pass it (to add to it) the integer that we pass in to this add method.1544

Now, when we go ahead and run our script, we are going to see that the same thing is output,1552

because if we look back here, when we call int1-->add(1), what we are doing is saying, "Call the add instance method on this instance of the integer."1555

It is going to go to our Integer class; it is going to call this add method, which then calls this static method addIntegers.1564

And it gives it the value and says, "Add the current value of this Integer object, plus the value that we passed in."1571

And when we refresh our script, it is going to show the same thing.1577

That is a way to also access a static method within another object method.1581

Just to try and sum things up in maybe a more visual fashion, we have this class/object diagram that we looked at a little bit when we first introduced objects.1591

Let's say we have this Person; this is a class that we defined in a class definition file somewhere.1604

And this is shorthand; this isn't correct syntax; but let's say we have defined three properties for this Person class.1608

firstName and lastName are both instance properties, so they are particular to each instance of a class.1615

And then, we are defining a static property, called desc, which is short for description.1622

And so, that is going to be a property that is the same for all of the different instances of a Person class.1627

Then, we are going to define two methods: we are going to define an instance method called getFullName,1633

which is going to operate on a particular instance of a class.1638

And it is going to have access to the instance properties of a particular class.1641

We are also going to define a static method called getDesc, which is just going to return the value of this static variable description.1645

And so, this is a static method.1655

When we create...for example, if we use the new keyword, Person, every time we did that, we would be creating an instance of the Person class.1657

This is an instance of the Person class; in this case, maybe we would assign it to the variable called person1.1669

So now, we have an object, and an object is an instance of this class.1674

And an object gets its own copies of instance properties.1678

We are going to assign Joe, for example, to the firstName instance property, Smith to the lastName instance property.1682

In addition, it gets its own copy, in a way, of getFullName.1689

So, when you call getFullName on this instance (maybe you would call it like this...and maybe it would return the concatenation1693

of firstName and lastName), this method is an instance method that has access to these instance variables.1702

Essentially, what I have shown is that here, we have just created two objects, person1 and person2.1709

You can see that the properties that are instance properties and the instance methods 1714

get their own copy made in each instance of an object that is created.1720

However, this static method stays up here; and so, when you access a static method or a static property,1725

it is almost like you are calling them on the class itself.1734

Whereas down here you would access the instance properties or instance methods using the arrow operator; 1737

now we have this new scope resolution operator to access static properties--in this case, description.1743

And that is how we would access that.1753

It is kind of like all of the things that are static stay in the class.1756

It is almost like a class, in a way, is an object of itself; it has its own properties, and it has its own methods.1760

In this case, it has its own description method that is specific just to that Person class.1766

It has its own getDescription method, which is specific to that Person class that anybody can call (assuming they are public methods).1771

But it doesn't have access to these instance properties of these instance methods.1778

Those are particular to each new object that is created.1783

Again, this is kind of a tricky concept, which is why I am focusing on it a lot.1788

It is just that when you create an instance of a class, any non-static properties or non-static methods1795

(which are instance properties and instance methods) get their own copy created for that particular instance.1803

The static properties and the static methods don't get copied; they have one copy1809

that resides in this global class definition that all of the objects have access to.1814

And it is shared between all of the instances of the objects.1820

One other related topic is class constants.1826

We know how to define constants within our regular scripts.1829

Well, you can define a constant within a class that is specific to that class.1832

You do it with a const keyword, and then you define the constant as you normally would.1835

Here, it is just alphanumeric characters--the same rules for naming a variable, except there is no dollar sign.1842

And the convention is still to capitalize all of the letters of a constant's name.1850

And then, you provide it a value.1855

So here, we are declaring a Math class, and we are declaring a constant in this Math class called PI, 1857

and setting it equal to the approximate value of pi, 3.14.1863

The way you access a class constant: because it is a constant, it can't change, so it is going to be the same in all the different classes.1867

So, it makes sense that you would access it kind of like a static property.1874

And you do that outside the class using the scope resolution operator again.1877

So, you have the class name (in this case, Math), and the scope resolution operator, followed by the name of the constant.1883

That is how you would access that from outside the class.1890

Inside the class, you would use the self keyword.1892

And then again, notice: the one thing here is that there is no dollar sign.1895

If PI were a static property, you would access it maybe like that after the scope resolution operator.1899

That is one key thing to note between static class properties and static class constants: the absence of the dollar sign.1907

Let's take a look at an example of that.1916

I created a class called Circle; we defined a constant in it, PI.1919

PI equals 3.14; and then, we defined a static function, which is a function that is just particular to the Circle class.1924

Anybody that knows about the Circle class can access this public static function.1932

And what it does is calculates the area of a circle.1939

You pass it the radius, and the formula for the area of a circle is pi, r squared (pi times the radius times the radius).1941

What this function does is accesses this class constant PI using the self keyword in the scope resolution operator.1949

And then, it says to multiply it times the radius twice.1957

You can call this function in a stand-alone way, and you call it the same way that we learned about accessing static methods.1961

And you would call it by using the name of the class, Circle, the scope resolution operator, 1969

the name of the static method that we want to call, and then also the parameter that we are passing.1973

We are saying we want the area of a circle with radius 2.1980

This is an example of calling this area static method on a Circle class that makes use of this constant PI.1983

And then, up here, we just have an output statement that shows how we access the class constant PI outside of the class.1991

And we use Circle (the class name), the scope resolution operator, and then the name of the constant.1998

And that, again, is different from when we access it within a class method, because here we use the self keyword.2005

So, if we were to go ahead and load this, we can see that it outputs the value of PI as 3.14.2013

So, we were able to access that class constant, using the scope resolution operator in the class name Circle.2022

And then, we were also to calculate the area of a circle with radius 2 by accessing that static method called area,2028

using the Circle class name, the scope resolution operator, and area.2034

For the homework challenge, what I would like you to do is build upon the Circle class that we just talked about from lecture example version 5.2043

And what I would like you to do is add an instance property to this class, called radius, that is going to represent the radius of a circle.2050

And add a public static property called numCircles, and we are going to use that as an instance counter.2057

What we are going to have you do is create a constructor that takes a radius as its parameter.2065

And what it is going to do: it is going to set that radius instance property that you are going to be declaring equal to whatever value you pass in.2069

And then, also, in the constructor, it is going to increment the static property numCircles by 1.2079

So, that is going to keep that reference count, because that numCircles is going to be for all of the Circle classes.2085

I also want you to create a destructor that, when it is called, decrements numCircles by 1.2091

And so, every time a object is created, that static variable numCircles is going to be increased by 1.2096

Every time an object is destructed, it is going to be decreased by 1.2101

Then, just output the value of the constant PI, which is already defined in the class that we saw.2105

And that will just give you practice accessing a class constant using the scope resolution operator.2110

Use the static area method, just like we had in our example, to output a circle with the radius of 2.2117

And then, I want you to create an instance of the Circle class.2127

Pass the constructor a value 2; so what it is going to do--the Circle constructor should take the value 2 and set its instance property radius equal to 2.2131

And then, create a calcArea instance method, which is going to calculate the area of a particular instance of a Circle object.2144

This is going to be an instance method, not a static method.2157

It is going to have access to the $this variable, so you will be able to access the radius using this, followed by the arrow, followed by 'radius.'2162

Use that, and within your calcArea method, you will be able to grab the value of the radius property 2173

of that particular instance, calculate the area, and return it.2182

And when you call it--let's say you defined a circle variable and you call it circle1--you would be calling this method using the arrow operator.2186

And note that we don't have to pass it the value of 2, because the circle object already has a radius property defined 2199

that already knows about it; and that is how you access it with this.2206

Repeat steps 6 and 7 for another Circle; so basically create two Circle objects.2211

Then, output the value of the static property numCircles after you have created these two, and you should verify that the value is 2.2216

That shows that you are properly incrementing that static variable that is keeping track of our instances.2222

Then, destroy one of the Circle objects by just setting it equal to null.2228

And then, re-output the numCircles property and verify that it has been decremented to the value of 1.2231

And so, that will give you practice with accessing the static variable outside of a class, so you would be accessing numCircles.2237

This homework example will give you practice accessing class constants, class static variables or properties, and class static methods.2254

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2264

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be discussing the details of the advanced course's development environment.0005

Specifically, we are going to be going over what the setup of our development environment for this course is going to be.0013

And then, we are going to go over what directory structure the files we are going to be using in this course are going to follow--0019

for example, how the web application directories are going to be organized; 0027

how the lecture examples and homework solution directories are going to be organized.0032

We are also going to talk about some software written in PHP called PHP Documentor,0036

which is something that we are going to be using in this course to document 0042

all of the web application function files and class files that we are going to be developing.0046

And we are going to explain a little bit about what that is and what that documentation looks like.0052

We are also going to have a quick note for previous Educator.com PHP students who have taken the introductory course,0058

to just mention some slight changes that have been made to the Educator Store web application 0064

from the end of the introductory lesson and to the beginning of this advanced lesson.0070

And then, we are going to introduce our first homework challenge for this course.0074

And homework challenges (for those students new to Educator.com, are challenges that are provided at the end of many different lessons0078

to give you extra activity to work on, so that you can reinforce and learn some of the concepts that we went over in a particular lesson.0088

The development environment setup we are going to be using for this course is the same that we used in the Introduction to PHP course.0098

And that is comprised of a couple different pieces of software--specifically the Firefox web browser (that is the web browser0106

we are going to be using for our development).0113

We are also going to be using the XAMPP for Windows software distribution.0115

And for those of you new to Educator, the XAMPP software distribution is a software package that bundles PHP along with0120

the Apache web server, and makes the installation and configuration of those two easy.0128

And in addition, it also provides the MySQL database.0133

And because in this advanced course, we are going to be dealing with the MySQL database, 0136

we are going to take advantage of that piece of software that is added to the distribution, as well.0140

Additionally, we are going to be editing our text files and doing our code development in the PSPAD text editor for Windows.0145

If we go and look at our web browser, you can see that Mozilla is the maker of the Firefox web browser, 0153

so this is the page that you will go to to download the Firefox software.0162

And all of these links are available in the introductory lesson.0166

This website, called apachefriends.org, is the maker of the XAMPP for Windows software distribution.0172

And this website tells a little bit about the different versions of the software (for example, Apache, PHP, and MySQL)0178

that are included in the distribution we are going to be using.0184

And then, pspad.com is where you can download the text editor that we are going to be using.0187

Additionally, we are also going to be using the Firebug add-on to Firefox, which is a web development tool0195

that you can add on to Firefox to help you when working with web applications and diagnosing different problems.0203

And if I click on this (it's already installed) little bug down here at the bottom of the screen, you can see the Firebug add-on pop up.0209

We will be working with that in this course--specifically when we are learning about HTTP and how that works.0216

In lecture 3 of the introductory course, that contains all of the instructions 0228

for setting up the development environment we are going to be using in this course.0231

So, for those of you that are new to Educator.com, I encourage you to go check out lecture 3 to find out how to set up the environment.0234

It walks through all of the different steps to get things up and running.0241

And what that is going to allow you to do is to hopefully be able to mimic the things that we do here in the lectures on your own home computer.0246

Additionally, there is lecture 28, titled Sending Email using PHP, that is part of that introductory course.0254

And that also makes some configuration changes to the development environment that allow you to send email from your PHP code.0261

And we use that in our Educator Store web application.0270

As far as the course goes, the course examples (the web application, the lecture examples, 0278

and the homework solutions) are all going to be combined into a particular directory structure.0288

And when you go to the Advanced PHP course's website, you will be able to download a ZIP file0293

that contains all of the homework examples, lecture examples, and versions of the web application.0298

What I am going to do now is just go over the structure of that ZIP file and how these files are going to be structured0305

within our web tree, or the document root of our Apache server.0313

The first thing is: we are going to be creating a file called advanced_php in the document root of Apache.0317

If we go to that, I have already gone in and unzipped this file that you are going to be able to get on the website.0325

And if you look in XAMPP, if you go to the XAMPP installation directory, there is an htdocs folder,0332

which is the document root of the Apache web server, bundled with XAMPP.0342

And we have an advanced_php folder.0346

Now, within that folder, there are going to be three different folders: one that is homework_solutions,0349

which has a folder for each lecture that has a homework challenge and provides a solution for it.0354

There is also a lecture_examples folder, which provides copies of all the examples that we run as we go through the lectures in the course.0361

And probably most interesting is the web_app folder: and what that does is contains all of the different versions of the Educator Store0371

web application that we are going to be developing and building on as we go throughout this advanced course.0377

For each version of the web app, there will be a separate folder that is going to contain all of the files for that particular version of the web application.0383

Here, you can see, we have version 0.0; and what that is: that is the baseline web app that we are going to start from.0390

Because we had already been developing this web app in the introductory course, we are going to baseline the app with version 0.0.0397

We are going to say, "This is where we are going to start from, and this is the version that we are going to add onto as we add new concepts in this course."0404

Additionally, there is also going to be a file called change_log.html within this web app folder.0413

What that is going to do is be an HTML file you can view in your browser that is going to allow you to see all of the different changes0419

that were made when going from one version to the next.0426

So, it will help you when looking at the different versions of the web app.0429

Rather than just looking at the source code to see the changes, you will be able to go to change_log.html and see any specific changes that were made.0433

As mentioned, what we are going to be using for this course, or at least the code that we are going to be including in the ZIP file0446

that you can download for this course, is going to be documented using a tool known as PHP Documentor.0453

And what it is: it is a tool that is used to automatically generate code documentation.0460

The way it works is: it parses source code files and looks for particular things known as tags and formatting structures that you add as a programmer.0465

And then, from those, you can generate documentation.0475

And if you take a look at, for example, outputLIB.php, which is our output function library,0479

and we look at the outputHtmlTag function, we can see that the documentation for this particular function has some strange tags in it.0487

And what they are, are ways to describe to the PHP Documentor tool information about the particular function.0499

For example, the @param tag is used to describe to the PHP Documentor all of the different parameters that a particular function takes.0506

The @return tag is used to describe the data type of the return value and what the return value represents.0516

There are a bunch of different other tags that we can use.0526

For example, here, this is an in-line source tag, which outputs in the documentation all of the source code for a particular function.0529

What happens is: PHP Documentor goes through and parses over all of these source code files and generates documentation.0539

Now, for this course, we are not going to be teaching how to use the PHP Documentor software.0549

But it is an extremely useful tool for generating documentation, and it is going to make it easier for me to explain0556

the different concepts that we will be learning throughout the course, and to look at the different source code,0563

because it formats source code in a nice, pretty format, and it is going to make it easier to describe things.0567

It is something that Educator will be doing on the back end; and with each version of the web application that we create,0574

and that we are going to include in the ZIP file you can download, there is going to be documentation generated for that particular version.0583

And it is going to be contained in the docs folder for each version of the web application folder.0590

For example, if we go to the advanced_php folder, and go to the web app directory, and we look at (for example) version 0.0,0598

we will see that there is a docs folder.0606

And it has an index.html file, which you can browse to, that is going to show documentation for all of the different functions,0608

and when we learn about objects and classes, all of the classes that are used in that particular version of the web application.0615

If we go...I'm going to go and show you what the documentation looks like.0622

For example, if we go to version 0.0 (and this is just browsing to this file in our web browser), and we go to docs, it automatically loads index.html.0628

And what you can see is: it has a rather nicely-formatted website, and it provides information 0639

about all the functions that we use in this version 0.0 of the web app.0646

For example, you can categorize the functions into different groups.0652

For example, I have categorized all of the output functions that are contained in outputLIB.php into an output category.0656

And it lists here all of the different functions that are defined in this outputLIB.php.0663

So, for example, if we click on the link outputHtmlTag, we can see the documentation that PHP Documentor has created for this particular function.0669

And what it did was: it went through and parsed this source code file that we have (and we talked about the different0680

tags that it looked for) and generates this documentation.0685

We can see, it has a statement about what the function does.0690

It returns a well-formed HTML tag, including any provided tag attributes and/or tag body.0693

It provides a little additional information that we can include to describe what the function does.0700

Here, we can see, it outputs the source code of that particular function.0705

And this is going to be useful to us, because when we are going over and explaining how the different versions of the web app work,0709

we are typically going to be using the documentation to look at the source code, because, as you can see,0715

it formats the code in a rather nice way; it does syntax highlighting, so that you can see things and make things clearer.0723

Additionally, it also has links to different functions.0732

For example, the one thing that the code automatically does is: if you use, for example, the is_string function0737

within one of your methods, you can click on it, and it will automatically link to that function's reference at php.net.0745

For example, if I click on is_string, it (and this is a little bit) goes to the php.net website and shows you the documentation for is_string.0752

And that is really quite a useful feature.0763

The other thing that it will allow you to do is (for example): down here, in the outputImg function,0766

when we look at the source code for it, we can see that it also calls the outputHtmlTag.0770

And if you will notice, outputHtmlTag is actually a link, and if we click on it, it goes and links to the outputHtmlTag's documentation.0777

So, it really is a convenient way to browse the documentation for different functions.0784

It enables you to figure out how the different functions work together, and how they are connected.0789

One other thing to note is that, if you want to look at the source code for a particular file...for example, if we want to look0796

at the source code for all of the output functions in outputLIB.php, if we click on outputLIB.php, it brings us to this page.0802

We can click on the link on the top that says Source Code for this File, and what it does is contains all of the source code that is contained in that file.0812

And this, again, shows it formatted in a nice way.0820

You can see here the different PHP Documentor tags, but you can also see all of the code that you have written.0823

We are going to be using that to look through the code as we work throughout the course.0829

If you want to find out more information about using PHP Documentor, and if you want to use that in your own code0834

(and I highly recommend it--it is a very useful tool), you can find information about that at phpdoc.org.0839

And one of the ways you can learn about how to use it is seeing the different tags that we used within our source code files for the course.0846

Now, I just wanted to briefly mention a couple of things for those students that are previous Educator PHP students that have taken the introductory course.0856

In addition to adding these PHP Documentor tags to all of our source code files, that allow us to create this documentation,0865

there have been a couple of other changes that have been made to the final version of that introductory web app.0874

A couple of things to note are that the LIB directory, where we contain our function libraries, has been moved to the Includes directory...0879

Before, LIB and Includes were two separate directories in the root directory of the web app version.0888

Now, the LIB directory is contained in the Includes directory.0894

Additionally, we have also moved the Images directory back into each version of the web app.0898

For example, each version of the web app...if we go to version 1.0, it has its own Images directory.0904

If we go to version 1.1, it has its own Images directory.0912

We had, in the introductory course, moved that out of that directory to demonstrate working with constants0918

and being able to change the location of an image directory and have your application still work.0924

But we did that to emphasize a point, but now we are going to use the Images directory in a more real-world application,0931

where it would actually be in the root directory of the web application.0937

Additionally, in our configuration file, config.php, we have gotten rid of the version constant.0941

And what we have done now is generated all of the URI's and paths that we use in our config file (for example) to load libraries and to load include files.0947

We are going to generate the URI's dynamically.0961

So, if we look at the old version of config.php, we can see we had a version constant.0964

And for each version of the web app, we would have to come in and update this version number.0971

And as you can see here, we used this constant to define the path to our particular version of the web application.0976

Now, what we have done is removed that constant and generated this root URI, which is the path we use to define (for example)0986

where our images are located in IMAGE_DIR, as well as where our Includes directory and our LIB directory are, and so forth.0998

We generate that dynamically, and we do that using the magic constant __FILE__, and then also using our SERVER ['DOCUMENT_ROOT'].1006

So, there is a little bit of code here at the beginning that will automatically generate that.1013

What that is going to do is: now, every time we update the version of the web application, we don't have to go and update that version constant anymore.1016

And finally, another thing that we have done is just updated some of the comments.1025

There were some comments that noted specific version numbers in the introductory course.1030

For example, there might be a comment that said, "This function was added in version 16.0."1034

Well, 16.0 is not relevant in this advanced course; it's version 16.0 in the introductory course.1038

So, we have gone ahead and removed those version numbers from our comments.1045

For the homework challenge for today, I would just like you to look through the web application source code1053

to make sure you understand how our web application is functioning.1058

You can go through version 0.0, play around with the code, and play around with the website to see how it works.1061

Additionally, I think it would be a good idea if you looked through the documentation that has been generated1069

by PHP Documentor for version 0.0, which is our baseline version for this course,1074

so you can get a feel for what the documentation looks like and how to use it, and how you can link, for example, from function to function:1081

how you can click on a link to go to the php.net website.1088

And it will just give you some experience, getting familiar with what that documentation looks like,1091

because we are going to be looking at that documentation a lot throughout the course.1095

Finally, for students that are new to Educator.com, I would like you to go ahead and (if you need to)1100

review lecture 3 and lecture 28 from the introductory course, to find out what you need to do 1106

to get your development environment set up on your computer, 1113

so that you can mimic the things that we do here in the lectures on your home computer.1116

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.1122

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application, 0005

incorporating what we learned in our last lesson about static methods and class constants.0008

In version 9.0, which is the version of the web application that we are updating to,0015

we are going to be creating an entire new class called Output, which we are going to use0019

to contain some static functions that are helper methods that are used to perform some simple, useful HTML output functions.0023

We are also going to be changing: previously, we had a buildItem object and a buildDept object function in our file library0033

that are used to build up a Department object or an Item object from a string that is read from items.txt or departments.txt.0041

We are going to be moving that functionality into each respective class, and calling it a buildObject method.0049

For example, Item is going to have a buildObject method now; it is going to become a static method.0057

And it is going to perform the same functionality, but it is going to be a static method within the Item class; likewise for the Department class.0062

First, we have the Output class that we have created, and it contains a couple of static methods for performing some common HMTL output tasks.0070

For example, a dropdown menu is a common HTML output.0080

And what we are going to be doing in this version is: we want to select an item from the database, maybe on an admin page.0087

And actually, I will just go to the page that I am going to show you.0093

In our administrator website, for example, what we are doing is creating dropdown boxes 0098

that allow us to select the Item that want to add to the Department, and the Department we want to add it to.0106

Previously, we just had a text box where we were able to enter the item ID.0112

Well, now what we are doing is dynamically generating these select boxes by reading from our store database,0115

from those flat files, and then generating those; and we are using these static functions to do that.0122

We have a general static function that we are creating called outputHtmlSelector, which just will return a well-formed select tag0129

containing all of the options that you specify for it.0137

We are going to look at that more in a second.0139

And then, we have two specific static functions for outputting a Department selector, 0141

to select any of the different Departments in the store, and also an Item selector, to select any of the different Items in the store.0148

And both of these methods call this generic outputHtmlSelector method, in order to be able to do that.0156

If we go take a look at our new Output class, we can see (for example): we have an outputHtmlSelector class method.0164

It is a static method, and what it does is builds up a select tag.0177

You provide it two parameters; one is the name of the select tag (and the select tag is an input tag, so it has a name,0183

so that when you submit the form that it is on, it is going to associate whatever option is selected with this name).0189

So, it is going to associate the value of the option selected with this name.0195

You pass it the name; then, we also pass it an array of options, which is going to include 0198

the value that we want to include in the value attribute of each option, as well as the text that we would like to include.0203

For example, if we look at our administrator website, here what we have (let's look at the source code)--0211

we can see that the output of this function is: we create a select tag with name itemID.0224

And then, for each option value, we have read from the database (and we'll go over that in a second) the item ID.0231

And then, we have output the name of the item and its item number as the text of the option tag.0238

For example, here...the format that the options array needs to be in is an associative array 0252

where the keys are the values that you want to include as the value attribute of each option, 0260

and the values of the array are the text that you want in the body of each option.0266

You can pass it any name in any array of any value and option body text pairs.0271

It will go ahead and generate all of those options within a select tag.0282

It will close it out, and then it will return that whole string--the select tag with all the different options in it.0286

What we do is make use of this in two other static methods.0294

One is called outputItemSelector, and what we do for that one is load all the items from the database.0297

This getItems method, as we know, returns an indexed array of Item objects--of all of the Items in our database.0303

And then, what we are going to do is build up an options array to pass to this outputHtmlSelector method that we just looked at.0310

What we do is: the keys of this options array are what we want as the values for each option tag.0317

So, what we are doing is: for each item that we pull from the database, we are setting the key in this options array equal to its item ID.0324

And then, we are setting its value equal to a string that contains both the item's ID and the item's name.0333

When we look at it, you can see that we have the item ID (which is 1001), and then the name.0340

And so, we do that for each item in the store, and it is going to build up this options array.0350

And then, we call that static method; and here we are using the self keyword.0356

And as we learned in the last lesson, that is how you call a static method from within another method of the same class.0360

We have self, followed by the scope resolution operator, followed by the name of the static method we are calling (in this case, outputHtmlSelector).0373

We want that select tag's name to be itemID, so that when the form gets submitted, 0381

whatever value is chosen is going to be associated with the name itemID.0387

And then, we are going to pass it this array of options that we built up, which contains values for the option tags,0391

which are the items' ID's, as well as what text to output, which is a combination of the item ID and the item name.0396

Now, we have also done basically the same thing for departments.0403

We load all the departments from the database into an array, and then we build up an options array.0408

And what we do is set the key of each option array to be the department ID of each department.0414

And then, the text that we are going to have for each department is going to be the department's ID, followed by the name.0419

And then again, we call this static outputHtmlSelector that is in the same class as this method is defined in.0425

So, we use self and the scope resolution operator.0435

We give it the name deptID; that is the name we want the select tag to have.0438

It is the value we want for its name attribute.0441

And then, we pass it this options array we have generated that contains the department ID's as the values, 0443

and then a string of the department ID and the department name as the text.0450

So, when we go and look at this, we can see that our output is the department ID, followed by the department name.0456

And so, what we can do now is: instead of just knowing what an item ID is and having to type it,0464

we are able to (and this will change any time we add a new item to the database)...it is going to automatically update it to this select box,0469

because this select box calls getItems, which draws from the database.0477

For example, let's just show what this looks like first.0481

If we look at our store, in the Sporting Goods department we have two items: a baseball bat and a basketball.0486

Now, let's say, just for fun, we want to add the winter jacket to that Sporting Goods department.0491

Well, we simply select Winter Jacket and Sporting Goods, Add to Department.0496

It is going to say, "Winter Jacket was successfully added to Sporting Goods."0501

If we go back and refresh our Sporting Goods page, we can see that Winter Jacket is now in that department.0504

It is the same functionality we have had before, but we have made it easier to use.0509

Now, let's say we go ahead and add another item to the website.0513

Let's see, a soccer ball--$25...a description...pick a random image...I'll just give it the image of the basketball, since that is one we have on here.0518

Add the item to the store; the item was successfully added--it has been assigned a new number.0539

If we go back and we look at the store, we can view our cart; we can see that this soccer ball item has been added--it's item 1007.0544

However, you would think it would be in the Sporting Goods department; 0555

but when we go to Sporting Goods, it is not in there, because we have not added it.0557

With our new interface, now when we click Add Item to Department, it is going to automatically load that new item.0560

Refresh the page, and now we can see that Soccer Ball has been added to the list.0567

We dynamically generated this list, where we can select any item we want from the store.0571

It is quite a neat feature; and we can add it to our Sporting Goods department and click Add to Department.0577

Go back and refresh our Sporting Goods page; we can see that that new item has been added.0583

So, we have taken the same functionality, but we have made use of the static functions 0587

that we have included in this Output class to dynamically generate these select tags.0592

And so, what this Output class is, if we look at the source for it, is simply just a class of public static functions that you call using the...0601

Actually, I haven't shown you how to do that.0616

If we go look at Add Item to Department, previously we just had text fields for the item ID and the department ID.0618

Now, instead of outputting a text field, we output these select boxes.0628

So, if we go down here, we can see, in the same spot: we are calling these static methods defined in the Output class.0632

We are saying, "Call the static method outputItemSelector defined in the Output class, and output the result of that method."0639

In this case, it is going to be a select tag.0648

We do the same thing down here for the department: call the static method and outputDeptSelector in the Output class, and return an outputted value.0650

And here, again, the way we access static methods from outside the class definition is by typing0659

the name of the class, followed by the scope resolution operator, 0665

and then the name of the function that we want to call and its parentheses, and if optional, any parameters.0669

That is how we make use of this Output class.0677

And these are functions that we could have just added to our...for example, we already have an outputLIB file;0680

we could have added these functions to here, as well.0689

But sometimes you will see that classes are defined with just a bunch of static methods in them; it is a different way of doing things.0691

And so, we are showing you that you can have some output functions, just as regular functions defined in the file library;0700

or you can have them defined as static methods within, for example, an Output class.0707

The other main thing that we did in this version of the web application is: we didn't get rid of, but we moved,0715

the buildDepartmentObject and buildItemObject methods that were in our file library.0722

We made them static methods called buildObject within the Item and Department class.0731

For example (let's close this), in our previous version of the web application, in our file library,0738

we had buildDepartmentObject that would take an array of information extracted from a line in departments.txt.0745

It would create a new Department object, and by reading the information from the array, it would set the ID of the department.0755

It would set the name of the department; and then, it would loop over each of the different ID's and add those to the department, using the addItem method.0773

Similarly, for buildItemObject, we would pass it an array of information extracted from a line in items.txt.0782

And we would simply build up an Item object using the Item constructor, and then return it.0789

What we do in the new version is (you will see in our file library): those functions no longer exist.0795

And if we go, for example, and look at item.php in our Item class, we can see we have a new function called buildObject.0801

It is a static function that returns an Item object, or false if there is an error.0810

And it takes a string, which is an Item string.0814

So, what we have done is: we have added the part that...0816

Before, what we had been doing is reading from the items.txt file, using the explode function0822

to take all of the data fields into an array, and then passing it to our buildItemObject function.0828

Now, we are just making it so that we are passing a line directly to this buildObject method.0833

We pass it an Item string, which if you remember...these Item strings that we output in our file 0838

are generated by the __toString method that we had added in a previous version of the web application.0845

And that defines the way that an object will be represented as a string, and that is how we store them in our file.0851

Whereas __toString converts an Item object to a string, this buildObject is going to take that Item string and turn it into an Item object.0858

And so, we have this static method buildObject.0869

And you just simply pass it an Item string; it calls explode on the Item data.0872

And then, it goes ahead and builds the object and returns it.0878

Now, one thing that you may notice is that the other thing that we have done is: 0881

we have moved the data separator constants from config.php into the Item class.0884

For example, if we look at the Item source code, we can see that now there is a constant declaration here:0892

const keyword, followed by the constant name DATA_SEPARATOR, and then followed by its value.0899

Here, instead of having a constant defined in config.php that is called ITEMS_DATA_SEPARATOR,0905

we just define a data separator function within an Item class.0913

And then, when we reference it, we reference it using the scope resolution operator.0916

And the way you do that is: in this case, we have not used the self method; we have just done the class name, which is another way of doing things.0929

You have the class name, followed by the scope resolution operator, followed by the name of the constant that we are getting.0941

And so, that is how we are able to access that class constant.0947

We have done the same thing for our Department object.0951

If we look at the source code for it, the Department object had two DATA_SEPARATOR constants.0955

One was to separate each of the data fields; and then, as we know, 0961

all of the item ID's in the department are separated by commas, so we have an itemID separator.0964

We have created constants, moved them out of config.php, and moved them into the Department class;0969

and then, we have also created this static buildObject function that takes in a Department string0975

that was created from the __toString method of the Department object.0981

We explode that string, based on the data separator.0985

We go ahead and start building up the Department object, and then we explode that third field, which is the comma-delimited list of item ID's.0989

And then, we add each item to the object, and we return the department.0998

What we have done is taken that method that was in our function library and moved it into our class library.1001

And in a way, it kind of makes sense, because it is something that is related to a Department object.1009

And one of the points of having classes to locate common functionality related to a common theme or subject into one area1014

(in this case, our Department class): if we have a function 1024

that is going to build a Department object, it makes sense to have it in the Department class.1026

In this case, we make it static so that you don't have to have an instance of the class created,1032

because all we want to do is: we already have a Department string, and we just want to build an object from that.1037

So, we don't need to access instance variables, so we have created the static method.1042

If we go and take a look, there are a couple of different methods where we have made use of this new function; and we will take a look at some of those.1047

For example, if we go to itemExists, what you can see is: what we have done is:1054

in this function, we loop over each line of the file, and we test to see if the itemID in each line is the itemID that we are looking for.1065

And this method takes a string that is an item ID that you are searching for.1073

What we do now is: we read a line from the file, and then we call this static method buildObject on Item, and we pass it the line.1078

Now, that line represents an Item object string.1086

As long as that Item object string is well-formed, meaning it comes from the __toString method of the Item, this will return OK.1089

And what that is going to do is: it will create that new item, and then we can access the itemID in that Item object we have built up,1097

compare it to the itemID that we are looking for, and if it is the right one, then we can break out of the loop and say,1104

"OK, the item has been found; exist equals true."1108

Then, the same thing for departmentExists...1112

We have also used it, for example, in getDepartment, getDepartments, getItem, and getItems.1115

For example, in getDepartment, we are extracting a line from departments.txt, and we are building a Department object out of it and returning that.1125

What we do is: we read each line from the departments.txt file.1135

We go ahead and call our new static method buildObject; we pass it the line and the file,1140

which is a string representation of a Department object.1145

This static method will build a Department object out of it; it will return it into this department variable.1148

We test to see if the ID of that department is the ID that we are looking for; and if so, it has been found.1155

And then, we can just simply return this department variable, because that contains the object that was built by buildObject.1162

And so, that is how these getDepartment, getItem, getDepartments, and getItems methods work:1169

by using these new static methods that we have incorporated into the class.1177

We have taken buildItemObject and buildDepartmentObject, moved them into their respective classes,1181

renamed them buildObject (and the reason we are not calling it buildDepartmentObject is: the way you would call it1187

would be Department::buildDepartmentObject, and it is kind of redundant, so we are just saying Department::buildObject),1194

and then we are able to pass it a Department string.1200

This buildObject is the analog of the __toString method we created in a previous version of the web application.1202

And in that case, we used to have a createItemDataString, createDeptDataString--we moved that into the class and made that into the __toString method.1208

So, we are taking a common functionality related to a department and related to an item, and focusing it,1217

and putting it all in that one class, so that it is in a related spot.1221

And so, what this shows us is an example of a static method, because this buildObject is declared as a static method.1229

And it shows how we have, for example, our Department class and our Item class:1238

unlike the Output class that only has static methods in it, our Item class and our Department class have instance methods.1243

They have instance properties.1248

Well, now we have added constants to them, and then we have added the static method buildObject.1250

So, this shows how we can have an object that has instance methods and instance properties, and also can have a static method to be called.1254

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1262

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be introducing the concept of exceptions, which is an object-oriented way of error handling.0005

We are going to introduce what are new structures within PHP code.0014

We are going to be introducing what are known as try/catch blocks.0018

And they are blocks that work in pairs to be able to handle errors in your code.0023

We are going to talk about a built-in class to PHP called the Exception class, which is used to encompass an error.0027

It is a class that essentially represents an error that has occurred.0034

And then, we are going to talk about a concept that will maybe be clearer as we go through it, known as re-throwing exceptions.0037

PHP provides a way to more gracefully handle errors.0046

Right now, the way we do it in code is: you can suppress the error, using the @ operator, and then maybe output a message on your own.0050

Or if you don't catch the error, PHP will just output a very terse, ugly error.0059

Well, what PHP does is provides a functionality called tri/catch blocks.0065

And what a tri block is: it is a section of code that you enclose within curly braces.0071

And when you encounter an error condition within your code (for example, you try to open a file, and you get an error),0079

instead of just outputting an error message there, what you can do is what is called throwing an exception.0085

And what it is, is signaling to the code that an error has occurred.0091

And what you do is use the keyword throw, and you pass it a new instance of the Exception class0096

(which you don't have to include the definition for in your PHP file--it is built into PHP),0105

which typically contains an error message that you are going to include.0110

And then, we are going to see in a second that there is a catch block associated with this that is able to handle these different errors.0114

Let's take a look at that.0122

When an exception is thrown--as soon as an exception is thrown (you encounter it; you throw an error), the code in that try block stops.0126

For example, we were executing some code along here in the try block.0132

We encountered an error, and we threw this exception; any code that was down here no longer gets executed.0136

Instead, what happens is: execution resumes down here to a catch block.0142

A catch block says, "If an Exception object that is of type exception has been thrown..."0147

And here we are throwing an object of type Exception.0153

And you can actually catch other types of exceptions, and that involves inheritance, 0158

which is a little more advanced object-oriented concept that we are not getting into in this course.0161

What the catch block does is: you can assign it to catch different types of exceptions.0168

In this case, we are just going to have it catch the generic Exception class that is provided by PHP.0172

We have some code along here; an error occurred; we throw an exception and set the error message for this Exception object to error.0179

What is going to happen is: code is immediately going to stop.0188

Nothing around here is going to get executed; it is going to go to the test statement; it is going to test if the exception thrown's class type was Exception.0191

Because it was, this is going to match, so what it is going to do is assign it to a value E.0205

And then, it is going to execute a section of code.0210

What this gives you the opportunity to do is: when that error is thrown, you can catch it and perform whatever sort of error handling you want to do.0215

In this particular case, as we will learn about, you are just going to be outputting an error message.0223

Let's take a look at a basic try/catch block.0229

Here, we have just a regular section of PHP code with a try statement.0234

And actually, we are not even testing for an error; to demonstrate the concept, we are just throwing an exception.0239

We are throwing a new instance of the Exception class--we are not even passing it any parameters, which is something you can do.0244

We have an associated catch block with this try block that is going to say, "When an exception is thrown up here, go ahead and catch it."0252

"And then, execute the code within these curly braces."0259

In this case, all we are going to do is output an error message that says an exception has been caught.0263

And because this throw always occurs, this is always going to execute; it is not conditional.0269

Typically, you would have some if statement that would say, "If this condition fails, then throw the exception."0274

In this particular example, we are just throwing it automatically to demonstrate.0279

Let's take a look at the example, and we can see that an exception has been caught.0285

What happened was: PHP ran this code; it got to this line; it says, "OK, this signals an error."0294

"I'm throwing an error; I'm stopping any code; and then, I go down here and process whatever error handling code is associated with that exception."0301

Now, one thing to notice is: let's say down here we had an echo statement, "Hello after."0309

I'm going to call it "Hello before"; so we have a statement before we throw the exception, and an echo statement afterwards.0317

Now, when you throw an exception, execution immediately stops in that code.0329

So, this line is not going to get executed; so if we go ahead and run this code, all we are going to see output is this Hello before, along with our exception here.0333

Let's put a break in there.0340

When we re-run our script, we are going to see Hello before, but we don't see Hello after.0344

And that is because, as soon as the throw occurs, execution of the statements in the try block stops.0349

And it is going to say an exception has been caught.0355

When an exception is caught, it is assigned to a variable that you can access within the curly braces.0362

We saw, in the last example, that it actually looks like this.0367

And here, you can define this in your code with whatever value you want.0380

What that says is, "This is going to catch any exceptions that are thrown within its associated try block,0383

and then it is going to assign the exception that it catches to this variable here that you declared."0390

In this case, we declared it e, so if we wanted to access the different properties and methods of this Exception object0395

(which we are going to talk about in a second), you would do it using this e method (for example, e-->getMessage, which gets its error message).0400

And so, in this catch blocks, this is typically where your error handling occurs and allows you to gracefully exit,0411

rather than having some terse PHP error statement going out to your users.0416

The Exception class has a constructor that can take up to three optional parameters,0425

the first of which is an error message to associate with the Exception object.0429

And then, there are a couple of different methods that the Exception class provides.0433

The first one we are going to talk about is getMessage, and what that one does is: if you set an error message0438

when you create the Exception object, when you pass the error message as the first parameter to the constructor,0443

when you call this getMessage on that instance (so within our catch block, if we called it on e, for example--0449

if that is the value we assign to the exception we are catching), if we call $e-->getMessage,0455

it is going to output whatever message we passed in the constructor to Exception, when we threw the exception.0463

There is also a getFile function that is an instance method of exception, so we would call it $e-->getFile.0469

And that outputs the file where the error occurred.0477

And then, they have this similar function getLine, which tells you the line where an error occurred.0480

If we take a look at an example called fileError.php, we are going to try to open a file called tmp.txt.0486

And it is a file that...let me just double-check to make sure that it...doesn't exist.0492

And the file doesn't exist; and when you try to open the file in read-only mode, it doesn't try to create the file if it doesn't exist.0500

So, when we try to open it, it is going to throw an error.0507

So, we have our error suppression operator here that is going to suppress the error.0509

And then, we can test open to see if an error occurred.0513

If it returns false, then that way we know that we had an error; so we are going to enter this if statement, this conditional statement.0516

And what we are going to say is that we are going to throw an exception.0523

We are going to throw a new exception that has an error message, "There was an error opening the file."0525

What is going to happen is: it is going to get caught as soon as this is thrown.0531

Execution of the code jumps down here to the catch statement.0536

It is going to catch the exception, because it is of the Exception class.0540

It is going to assign it to the variable e, and it is going to execute the code within these curly braces.0544

What we do here is: we are simply taking this exception object that was caught;0550

we are calling the instance method getMessage on it; we are outputting the message, 0554

which is this error message we included in the constructor; and then, we are also making use of 0560

the getLine and getFile instance methods of the Exception class to output where the line and the error occurred.0565

For example, if we go ahead and run this script, we are going to see that there was an error opening the file.0573

"Error occurred on line 27 of" and then it lists the name of the file where the error occurred.0586

And that, again, is because this file doesn't exist, and when you try to open something in read mode, it doesn't try and create the file.0591

So, it is going to generate an error.0598

Let's say, instead, we try to open it in overwrite mode, which automatically creates the file, if it doesn't exist.0599

Then, this isn't going to throw an error; and so now, when we run this file, we should see no output,0608

because open is going to be true, which is going to evaluate to false, so this exception will never get thrown.0612

And so, I will put a little output message here--"after if statement," let's say, so at least we have some output.0620

And that is going to show that this if statement doesn't get executed, and then we output this message.0632

Now, the other thing to note, as well, is: once you reach the end of the try block,0638

if you have not thrown any errors, you don't execute any of the code within the catch blocks.0642

What you would do at this point is: in this case, after we reach this echo statement down here,0647

no exception was thrown--we jump over any catch blocks associated with it, and we beginning executing the next line of code.0652

Maybe let's put another output statement here, "after catch block."0658

What we are going to see, when we run this script, is: open is not going to cause an error, so we are not going to throw an exception.0672

We are going to execute this next line in the try block.0678

Then, we are going to skip over the catch block, because an exception was not thrown.0682

And then, we are going to echo any statements after that.0686

In this case, it is going to say "after catch block."0689

So, when we re-run our script now, we are going to say "after if statement," "after catch block."0690

So, you can see that the exception was not thrown, because there wasn't an error anymore.0696

And then, you can see how the try block continues to execute after a throw statement, if the throw statement never gets executed;0702

and then also that, after you complete all of the statements in a try block, you simply jump down to here.0709

You notice that none of these lines got executed here; we didn't have anything that said an error occurred.0715

That is because an exception was not caught.0720

If you never throw an exception, the code in the catch blocks never gets executed.0724

One other example is: you can throw exceptions from methods, as well.0731

In our case, we have just been throwing them from a first-level PHP script.0742

Well, you can also do it, for example, from object methods.0748

Here is a stripped-down version of the DataFile class we have been using in our web application.0750

It has an access mode, a filename, and then a file handle.0755

You pass into the constructor the name of the file you want to open and the access mode you want to access it as.0759

And then, we define an open function; and the open function tests that the file name is valid, and it attempts to open the file.0765

If it does, it returns true, and the fileHandle property of this class gets set to the handle of the open file.0772

Now, if fopen returns an error, what we are going to do is set fileHandle to null, and we are going to use an exception.0783

And we are going to throw an exception that says there was an error opening the data file.0789

And so, what is going to happen is: when that gets thrown, there is no catch block here, so what it does is0794

jumps to the end of this method and throws the exception to wherever this function was called from.0802

So, if we have a script where we create a new DataFile object, and we try to open it,0807

and this open method is called within a try block, this open method (because it throws an exception that doesn't get caught)--0811

we are going to catch it; it is going to be caught here, because we have a catch block.0818

And then, we are going to be able to output the error message.0823

The other thing is: for example, let's say the filename is not a valid filename.0826

Well, that is also going to be an error; so down here, we can throw an exception with a different error message,0832

saying "instance variable filename needs to be set," because the filename wasn't properly set when creating this.0837

Here is a way that we can use this high-level script that calls this to be able to output two different error messages, depending on which exception occurs.0844

And we do that simply by setting a different value of the error message for our Exception object.0852

For example, if we try to open a data file, and we pass it the filename null, what is going to happen is:0859

when we try to open it, it is going to cause an error, because it is going to test if filename is not equal to null.0865

It is going to turn out false, and so what is going to happen is: it is going to execute this else statement, which is going to throw an exception.0871

If we go and run this script, we can see the error message: "in the open function of dataFile.php, the instance variable filename needs to be set."0878

This is a way you can provide useful information to maybe your users, 0894

or also when you are debugging and things like that, to figure out where things are going wrong.0898

If we had just put 'error,' it is not as informative; so I always encourage you to, when you throw exceptions,0902

and you create error messages, make them as useful and as meaningful as possible, so you can really figure out what is going on.0908

Now, that is as opposed to...let's say, instead, that we pass it a valid filename, tmp.txt, that doesn't exist.0914

But we try to open it in read mode, and as we know, when we call open on a file in read mode that doesn't exist, it is going to throw an error.0929

So, our open method is going to enter this if statement, because the file is not equal to null.0935

But when it tries to open the file, it is going to throw an error.0941

So, what is going to happen is: this if statement is going to return false.0945

We are going to exit the else block, which throws this other exception that has a different error message0949

that says, "There was an error opening the file."0954

If we go back and save this, and we reload our script, we can see that we get a new error: "There was an error opening the data file."0958

That is how you can see how a method can throw an exception that you can catch outside of the class.0966

You don't actually have to catch it in whatever particular block it was defined in.0973

If an exception is thrown within a method, and there is no try/catch block, it will get thrown out to 0977

wherever that method was called from--in this case, in our script, exceptionFromMethod.php.0984

And here, because we have a try/catch block associated with it, we are able to catch it, and then output the error message stored in the Exception object.0990

One thing that you can also do is re-throw exceptions.1001

That means that, if you catch an exception, instead of handling it and just outputting an error message, you can re-throw it.1004

We just learned that you can throw an exception within a method.1011

And if there is no catch block for it, it will be caught in whatever script called it, assuming there is a try/catch block there.1017

Well, what you can also do is: if you have a method that has a try/catch block in it, and it catches an exception,1023

it can throw the error again, which is going to throw it to whatever method caught that.1029

And then, in that case, what you are doing is: it is like this chain of throws, where you can pass it up to wherever you eventually want to handle it.1035

It is more easily understood if we look at an example.1042

Let's say we have this DataFile class that we have created a new function in.1046

It is the same as before, except we have created a new function called appendLine.1050

It is just to append a line to this data file.1054

In this appendLine function, the first thing we do is try to open the data file represented by this class; we call the object method open.1058

Well, we do this within a try block, because we know that this open method can throw an exception.1067

So, in our file, we are going to try to open this file that doesn't exist, so it is going to throw an error.1074

What is going to happen is: this is going to call this open; this open is going to throw an error.1087

Down here, we have a catch block that is going to catch the exception thrown by the open method.1094

And then, instead of outputting an error message here, it is going to re-throw that.1098

And simply, what it does is: you can say throw, and then you can pass it the object that represents that exception.1103

And then, what is going to happen is: whatever method called appendLine has the opportunity to catch that exception.1109

So, in our main script, what we do is declare a new DataFile object that is going to end up causing an error when we try to call appendLine.1116

And then, within a try block, we call the appendLine method with 'Hello, World!'1125

And so, what is going to happen is: we are going to call appendLine.1130

It is going to go into appendLine, and it is going to try to open the file, which is going to go up here.1135

It is going to encounter an error and throw an exception.1139

We are going to catch the exception here.1142

Instead of handling it here, within the object code, we want to handle it, for example, in our script,1144

because that is where we output things to the user.1149

We re-throw it; we have a try/catch block where we call this appendLine.1151

And so now, this exception that occurred two function calls deeper--we catch it in our main script, and then we can output the error message.1156

When we try to append this line, we are going to get the error message that says, in this case,1168

"The file could not be opened," because you can't open this file for reading, because it doesn't exist.1173

If we go and try to run this script, we can see that there is an error opening the data file.1179

We eventually called that method open by calling it from within appendLine, and open threw the exception1188

that appendLine caught, that re-threw it, that our main script caught, that was able to handle it.1197

And what this allows you to do is keep throwing errors down the chain of method calls,1201

until you get to a spot where you want to be able to handle it.1207

In this case, we didn't want to handle the error in this appendLine class, let's say,1209

because typically we want to keep our output separate from our programming logic.1216

So, instead of outputting HTML here in this appendLine function that said there was an error thrown,1222

we are just going to re-throw it up to our main script, which we use to output information to the user.1226

And then, we are going to output the error message there.1232

That is an example of what is known as re-throwing exceptions.1235

For the homework challenge, I want you to create a script that defines a function called divide--1241

just a regular function--not a class function or anything.1246

It takes two parameters that are numbers that are to be divided.1249

And what it is going to do is test if the divisor parameter (which we will have be the second parameter;1253

so the first parameter is going to be the dividend, and the second parameter is going to be the divisor) is equal to 0.1259

If it is equal to 0, I want you to throw an exception using that Exception class.1264

Throw a new exception, and then include an error message in the constructor of Exception that says, "Division by 0 was attempted."1269

That is if it is equal to 0; if the divisor is not equal to 0, then simply divide the dividend by the divisor and return the result.1277

In the same script, after you define the function (instead of defining it in a separate function library, 1286

you can just define at the beginning of the script for this simple example), go ahead and call divide twice:1292

once with the numbers 10 and 5 (so that is going to try to divide 10 by 5).1298

And then, try to call it a second time with 1 and 0 (so it is going to try to divide 1 by 0, which is going to throw an exception).1301

Call both these methods within a try block, and associate a catch block with that try block that will catch an exception.1309

And it is going to catch that divide by 0 exception.1317

And what it is going to do is assign it to a variable, maybe $e.1320

And then, I want you to output the message that is associated with that exception.1325

And that message that is going to be associated with it is what you set when you throw the exception originally, when you call its constructor.1328

And then, when you run the script, you should verify that you see the output of 10 divided by 5 is going to equal 2.1338

And then, instead of seeing another output of 1 divided by 0, you should see your error handling code1343

that says, "An exception has occurred; you tried to divide by 0."1349

That will give you some experience with working with exception handling.1354

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1358

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application,0005

incorporating what we learned in our last lesson about exceptions.0008

In today's lesson, we are going to be going through two different versions of the web application.0013

We are going to have a version 10.0 and a version 10.1.0018

In the first version, 10.0, first, we have made a couple of changes to our admin site, 0022

particularly to addItem.php and addItemToDept.php, which are two administrator pages.0031

What we are going to do is remove the old error handling process that we had before.0040

And instead, now we are going to use exceptions to manage error handling.0045

We are going to include some try/catch blocks to demonstrate how to use those try/catch blocks in a real-world application.0051

As part of that, we are also going to be creating a new admin page called error.php.0061

What is going to happen is: whenever an exception occurs on one of our admin pages (either addItem.php or addItemToDept.php),0066

it is going to catch that exception, and then what it is going to do is: the application 0074

is going to redirect the user to this error.php page, which will output an error message.0078

So, first of all, let's look at our old addItem.php page.0086

The way we have done our error handling is: we have an error flag and an error message variable that we use when we encounter an error.0095

For example, if there was an error adding an item to the store, then we set the error flag to true.0104

And we say, "The data provided for the new item was invalid."0115

And then, down here, in our output section, we test to see if the error flag was set.0120

And if it was, then we skip our typical output and output the error message.0124

What we do in our new version is: in the top, we (let's take a look at it) enclosed all of our data processing section in a try/catch block.0130

So, what we do is enclose all of our data processing in a try block.0147

And what we do is: for example, in addItem.php, we create a new Item.0154

If the Item is not valid (this isValidItem is our function that tests whether the new item has been provided all the correct information--0161

whether a correct image has been uploaded, and so forth), then what we are going to do is throw an exception0171

that says, "The data provided for the item was invalid."0181

Then, when we try to insert the Item into the store, another exception can occur if there is an error with the insertItem function.0185

So, if insertItem returns false, then what we are going to do is throw an exception that says there was an error adding an item to the store.0192

Well, because we have a try block, we also have a catch block associated with that.0200

This is going to catch either of these exceptions, so if either of these exceptions occur, it is going to catch the exception.0205

And it is going to be accessible by our variable E, which we can access within the catch block.0210

And what we are doing is using the header function that, when used with the Location header, allows us to redirect the user to a new page.0216

If an error occurs, we catch the error, and then we are redirecting the user to error.php.0226

And what we do is: we are providing error.php, by a query string, a GET variable called error.0231

And we are simply providing the message that was in whatever exception was caught, and we are URL-encoding it.0238

If we look at error.php, what it does is processes a GET variable at the very beginning,0247

which it tests for the error GET variable, which is provided in our query string.0253

And then, if an error message was provided (meaning the error GET variable was provided),0259

then what we go ahead and do is output the error message, if one exists.0266

And if not, we just say an error occurs (like, for example, if somebody had just randomly gone to error.php).0272

The same thing happens for addItemToDept.php.0280

In our old version, had our error flag and our errorMsg variables that we used to report errors.0283

If there was an error adding the department, we set the error flag.0290

If there was an item ID or department ID that was invalid, we set an error.0294

And then, in our output section, we tested if an error had occurred; and if so, we output a message.0300

Well again, similarly, what we are doing in this new, updated version (version 10.0): 0305

we are encapsulating our data processing section at the beginning of the file in a try block.0311

And any time an error occurs--for example, if the addition of the item to the department was not successful--0318

we are going to throw an exception that says there was an error adding the item to the department.0324

If some of the data provided on the form is invalid, meaning that, for example, the item or the department ID provided is not a valid ID,0330

then we are going to throw an exception that says the data provided on the form is invalid.0338

Again, we have an associated catch block, and it is going to catch an exception.0343

And it is going to associate it with the variable here; again, we have chosen E.0350

And again, we are going to redirect the user to error.php and simply provide, via the GET variable error...0355

we are going to set the GET variable error equal to the message encapsulated in our Exception object.0363

It is going to forward it to the error page, and the error page is going to have the same output.0369

If we go and take a look at our Educator store, and we look at the admin website, here is our addItem page.0373

And let's say we try to add a new item, but...let's provide an image...let's say we don't provide a description.0381

And as we know from working in our web application before, all of these are required fields.0395

So, what is going to happen is: when addItem is processed, it is going to test all of these data fields in the isValidItem function.0400

What is going to happen is: it is going to return false, because we didn't provide a description.0411

So, this exception is going to get thrown that says the data provided for the new item was invalid.0415

The exception will get caught, and we are going to get redirected to error.php.0420

When we go ahead and click Add Item, it is going to direct us, if you look at the browser at the top, to error.php.0424

I'm not sure if you will be able to see the text big enough.0434

You can see that the error message was appended as a query string.0435

And we have set the error GET variable equal to a message that says the data provided for the new item was invalid.0441

And then, you can see here that our page goes ahead and accesses that exception message and outputs it on the page.0448

And the same thing works for addItemToDept, when, for example, an error occurs in adding the item to the department.0455

The other thing that we have done is: we have also added, in our DataFile class, an open method,0467

which is used to open the particular data file (for example, items.txt, departments.txt, or lastAdded.txt).0473

And when we open the file, a file open error might occur.0481

And if that occurs, then it is a fatal error, in a way, in that our application is not going to work.0484

What we are going to do to handle that: whereas before, what we did in our previous version of the application0491

is just to directly output an error that says, "There was an error opening the file";0496

now, what we are going to do is use exceptions to handle that error.0501

So, what we do is: we are updating our open method so that, rather than outputting an error message, it is going to throw an exception.0507

Then, whatever method calls our open method is going to surround the call with a try/catch block,0515

so that it can catch that exception that occurs if there is an error opening the file.0524

For example, if we go and look at our documentation for (let's blow this up a little bit) DataFile,0529

and if we look at the open method, we can see that what we have done...0543

And actually, let's go ahead and open up the old version, as well.0548

If we look at the open method in our old version, if there is an error opening the file, we output an error message0564

that says, "There was an error opening the data file," and we simply output that to standard output, which is going to be output to the user.0572

Well, instead, in our new version, what we do is: when an error has occurred, we throw an exception.0578

And what happens when that occurs is that the execution of that function stops, 0591

and whatever method called this open method is going to have to handle, or catch, this exception.0594

So, here we have, for example: if the fileHandle property was null (meaning that an invalid file name was provided0601

in the constructor to this DataFile class), it is going to say (formatting is a little messed up here)0610

that there was an error opening the particular file.0617

And then, what that is going to do is throw an exception if there was an error in the call to fopen in the file.0622

Down here, it throws an exception if the filename property was not properly set, meaning that you provided an invalid filename to the file.0633

So then, what happens is: for example, all of our functions in our file library 0643

that use the GET open method now are going to enclose things in try/catch blocks.0648

For example, in our getItem function, which loads an item from the database, what we do is:0654

we declare a new DataFile object, and then we try to open the file.0661

And what we have done now is enclosed that in a try block.0667

And what happens is: we catch the exception, and then, right now, we are simply returning false.0672

We are not outputting any error message, which is different from our last version, in which what we did is:0676

when we called the open method, we enclosed it as a test for our if statement, because open will return true or false.0693

And if it returns false, then we can say, "OK, we are going to return false from the method."0702

What we have done in our new version now is used a try/catch block instead.0707

So, rather than enclosing this in between the if's parentheses, we simply...if it doesn't throw an exception,0711

it is going to continue executing the code in the rest of the function.0721

If an error is thrown, then it is going to know that an error was thrown, and it is going to return false.0725

And we are going to see, in the next version of our application, that we are going to show a way to log that error,0731

so that we can find out information about it.0737

Right now, all that happens is: when a user tries to get an item (for example, when you go to item.php0739

and it tries to load the item from the database), if there is an error (opening the items.txt file, for example),0745

all this method is going to do is return false, and it is not going to allow you to load the item.0753

But it doesn't really provide any information to the user.0758

Before, in our old DataFile class, we had, in the open method, output an error message, stating that you couldn't open the file.0760

But that doesn't look very good if that happens--if it just outputs a random error message to the user.0778

So, what we are going to do is: we are not going to output an error message in our next version of this web application.0783

We are going to show you how to log that message, so that it handles the error gracefully.0787

It doesn't show an ugly error message to the user, yet you still see that the error occurred.0792

All of our functions that use that open method (for example, getDepartments) all enclose the call to the open method within a try block.0798

And then, they catch any exception, if it occurs.0810

What we have done, in a new version of 10.1, is added a little bit of a feature to our web application that involves what is known as a logger.0819

And there are libraries out there that you can use that are logging libraries, that allow you to insert statements in your code0828

that allow you to log errors or warnings or debug statements that help enable you to debug your code.0837

We have created, for this, a simple Logger class; it is a new class.0844

It makes use of our DataFile class; and what it does is opens a log file, and it has a couple of static methods in it 0849

(for example, logError and logWarning) that, when you call these static methods, as a parameter you pass some message.0860

And then, what the Logger class will do: it will add that message to a log file.0869

For example, we have a file open error; because we are not outputting that message to the user anymore,0875

we can log it to this log file, and then when we have a problem with our web application,0879

we can look at the log file, and it will provide information as to where things went wrong.0883

As part of this, we have updated config.php with some log-related constants.0889

If we look at config.php, we can see that we have added a LOG_DIR constant.0893

What we have done is just added a directory called logs to our web root for this particular version of the web app.0900

And then, we have also created a constant called LOG_FILE, which is the name that we want to use for our log file.0908

In this case, we are going to call it log.txt, and it is going to be stored in this LOG_DIR directory.0916

If we go and look at this new class, Logger...let's go look at the source code for it...0922

we can see that it has two static methods: it has one called logError and one called log.0934

And what it does is: when you call the logError function, it takes whatever message you pass to it,0948

appends a statement that says "this is an error," and then calls another static method that is part of this class,0959

which actually goes through the process of opening a data file, which is going to be the log file.0965

It is going to open the file and append the message to it.0972

One thing that it also does is adds a date/time stamp to the beginning of the message.0975

So, when it logs it, it is going to have a date/time stamp.0980

It is going to say 'error,' and then it is going to have whatever message you include in there.0983

So now, what is going to happen is: whenever we throw an exception (for example, we throw an exception 0987

when we try to open items.txt using our open method of the DataFile class), whatever method 0995

(for example, maybe in our file library, the getItem method) is going to try to open the items DataFile...1002

when it throws an exception, now what it does is: when it catches the exception, instead of just returning false, 1011

it is going to make a static call to this logError function that passes it the message contained in the exception.1017

For example, in this case, because we are trying to open items.txt, if there is an error opening that file,1028

the exception that is thrown is going to say, "There was an error opening items.txt."1034

Here, we are appending a little information to it that is stating that this error occurred, also, in the getItem method of fileLIB.php.1040

Then, we call the logError method, which is going to call logError, which is going to append an error message to it.1049

And then, it is going to go ahead and write it to our data file.1059

For example, if we take a look at our website (blow it up a little bit), this is our Educator Store version 10.1.1062

We can see that it works as normal, if we look at our homepage.1077

When our homepage is loaded here, it is loading information about all of the different departments,1081

in order to output, for example, this left navigation bar.1086

It accesses departments.txt.1089

Well, let's say that we were to go and rename our file for this version departments.txt and call it departments.txt2.1093

Now, what is going to happen is: when this page loads, it is going to call the getDepartments function,1102

which is going to create a DataFile object, and it is going to call the open method on that DataFile object.1110

It is going to try to open departments.txt; it is not going to be able to.1117

So, what it is going to do is throw an exception.1120

The getDepartments method will then catch that exception; and if we look at our getDepartments method,1122

we can see that now, when it catches that exception, it logs the error to our log file.1129

So, if we go ahead and try to do this (now that we have renamed our file, and we refreshed the page),1135

here we can see that we get an error, so we know that an error occurred and that we can handle this a little more gracefully.1140

But the main purpose of doing this is to show the use of our log file.1144

What we can do is: if we look at version 10.1, there is a logs directory; there is a logs.txt file;1149

and if we go and look at it now, we can see a date/time stamp that says, "An error occurred at the 20th hour,1156

57 minutes, 37 seconds of the 2nd of September."1167

It is going to say, "An error occurred in the getDepartments method of fileLIB.php."1172

It is going to also say that the error occurred before that--it occurred in the open method of DataFile.php.1178

And then, here is the message that was contained in our exception that we threw.1185

"There was an error opening file," and if we look at this, "departments.txt."1188

And the reason that this shows up twice is because, on our homepage, we call that getDepartments method twice,1194

and we try to output the different departments here, as well as within our left-hand navigation bar.1200

And so, that is how our logger file works; and what it does is allows us to provide some information1206

that doesn't get sent to the user, but that we can look at our log file and debug things.1212

Also, what we have done is...for the close method of our DataFile class, that can generate an error as well,1218

if there is an error with closing the file that we have open.1225

However, because we have already extracted what information we need from the file, it is not necessarily a fatal error.1228

So, we are going to log it; in this case, we are going to log it as a warning, using the logWarning method,1235

which is also part of the Logger class, which appends a warning message to it.1240

And if we go and look at our Logger class, we can see that we have a logWarning function1247

that does the same thing as logError, except it allows us to...it appends a warning to whatever warning message we pass.1272

So, if we go and look at our DataFile class in the close method, whereas before we just had an echo statement1282

that would echo, "There was an error closing the file," now what we do is call our Logger.1297

And we have a log warning that says, "There was an error closing so-and-so file," or whatever.1301

And so, that way, we can at least look at our log file and find out if there was an error closing the file.1307

And that is a way to keep track of things.1312

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1316

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be covering the topic of cookies.0005

Specifically, we are going to be going over what a cookie is.0010

It may be something you are familiar with, or maybe it's a term that you have heard thrown around in the web development world.0014

We are going to talk a little bit about HTTP and how it is known as a stateless protocol, and how cookies can change that.0021

We are going to talk about a couple of HTTP headers.0031

We are going to talk about the Set-Cookie header, which is an HTTP response header.0035

And we are going to talk about the Cookie header, which is an HTTP request header.0039

We are also going to talk about a function built into PHP for what is known as setting cookies.0044

We are going to talk about different attributes that cookies can have.0055

We are going to talk about (after we learn about what cookies are) how to access cookie data within your file using the COOKIE superglobal variable.0058

And then, we are going to briefly talk about security implications as they relate to cookies.0069

What exactly is a cookie? Well, it is a piece of information or data that is set by an HTTP server,0077

and it gets sent back to a web client within an HTTP response for storage by the client.0086

For example (and it is done in name/value pairs), a server might want to set a cookie that says the user ID equals 1001.0092

Well, it will create that cookie, and then what it will do is: using an HTTP response header,0103

it will send that cookie back to the client, and the client is going to store that on its local machine.0109

Cookies are associated with a particular website, and what happens is: every time a client goes to request a page from a particular website,0115

it checks to see if it has a cookie stored that is associated with that website.0123

If it does, it goes ahead and, in its HTTP request, sends the information contained in that cookie to the web server.0128

Before we go into the details about how the cookies work, I just want to talk quickly about HTTP and what is known as a stateless protocol.0139

What that means is that, for each HTTP request and response, no state is preserved,0148

which means there is no memory between one request and another.0155

For example, when you go to a website, and you request a page...0158

for example, let's say this was your HTTP request, and then your server would respond with something like this,0162

with HTML as part of the body; when you do that request--let's say you do that multiple times--0171

each time you do that, the HTTP server has no idea that those are linked from the same computer.0179

It can know that it is from the same computer, but it doesn't store any information about each of the different requests.0187

For example, let's say that you were trying to implement a shopping cart, and you add an item to a cart.0195

Well, maybe what you would do is send a GET request that provides some information.0201

Maybe you have a query string that says to add item 1001.0206

And the HTTP server is going to go ahead and process that GET request.0212

It is going to add an item to a shopping cart, and then it is going to send the response back to you that maybe shows you your shopping cart.0216

However, the next time you go to add another item to the shopping cart, how does the server know that that item 1001 is already part of your cart?0224

HTTP, in and of itself, doesn't have a mechanism for that.0234

It doesn't store this information anywhere--for example, on the server.0237

Well, cookies are a way to enable some memory--some state--to occur between different HTTP transactions.0242

For example, cookies are to provide knowledge of previous events.0253

What it does is connects one HTTP request to another.0260

And this can be used for things...for example, it can identify a particular client.0263

Maybe, when you go to a website, and you log in, the HTTP server, when it sends you back your welcome page,0267

will send you a cookie, which is a piece of information.0276

And it is going to say, "Your user ID is this."0279

Then, every time you go and visit a page on that website, you are going to send that cookie back to the server, and it is going to identify you.0282

And then, the server can say, "Hey, this is a person I have dealt with before," and maybe it can alter its page content based on that.0289

Another thing that you can do is contain information in a cookie, such as the contents of a shopping cart.0296

For example, let's say you send an HTTP request; you click on a button that says "Add Item to Shopping Cart" 0303

that sends a GET request with the item ID to the server.0310

Well, the HTTP server can then create a cookie that says, "OK, maybe the cookie's name will be 1001, which is the ID of the item."0313

And maybe its value is going to set to 1, which means you added one of those items to your shopping cart.0324

Well, what the server can do is create a cookie that contains this data.0329

It can send that back in its response to the client.0333

And then, when the client goes to another page in that website (for example, clicks on the Add to Cart button0337

for another item on that website), well, because, as we had mentioned, any time you have cookies stored for a particular website,0343

when you go to a page on that website, you automatically send it; when you go to add that second item to the cart,0351

you are going to send this cookie back to the server.0357

So, now the server knows that you have already had one item in your cart.0362

And it can add this new item to the cart; it can update the cookie to reflect that.0366

But now that it knows this information about you having this item already in the cart,0371

when it sends you a page back to view your cart, it can show both of the items, because it has knowledge of that.0375

The way that setting and getting cookies works is through some headers.0383

In particular, there is an HTTP response header called Set-Cookie.0391

And what that does is: that is a way for the web server to send a cookie (which is a name/value pair) back to the client that has information.0397

An example of an HTTP response header that sends a cookie to the client is this right here.0406

We have our typical HTTP response information, and down here you have the body of the response.0413

Maybe it is the HTML to represent a shopping cart.0419

But what you can see is that it has a new header here called Set-Cookie.0424

And what you do is provide the name of the cookie, and then the value, to it.0427

The server is going to say, "OK, I am sending to this client a cookie that has the name cookie, and it is going to have the value equal to cookie value."0433

And what that is going to do is: it is going to get sent to the client.0446

When the client receives this response, it is going to store this cookie and associate it with whatever website this response came from, right here.0448

If we go and take a look at an example, I'm going to have Firebug open, and in the Firebug, we select the net tab,0459

so that we can see the HTTP header information that is going on.0469

For example, if we click on the script httpSetCookieHeader.php, this is a script that, 0474

when you go to it, creates a cookie and sends it back to the client as part of the script.0481

And we are going to talk a little bit more about how to do that in a few slides.0489

But for now, that is what is going on behind the scenes.0491

It just shows a little bit of output, of what the HTTP response when you go to this page might look like.0495

It is going to show some of your typical HTTP response headers.0502

And you can see, also, that it has a Set-Cookie header, which is setting a cookie named example1Cookie, and it has the value equal to value.0504

Now, if we go down here and we look at our Firebug output, and we see the HTTP response header that we get back0516

from the server when we requested this page, we can see, in the raw header, 0526

that there is this Set-Cookie header; and it has, as we expected, the name of the cookie and the value.0530

And so, that is how the server sends the cookie back to the user; it uses this Set-Cookie header.0538

Now, we have another script called cookieHeader, which shows the client side of things.0547

And what this shows is: when the client requests another page from this particular website0553

(in this case, it is a localhost website), what it is going to do is say, "Get me the page httpCookieHeader.php."0559

It is going to have the Host header, and then it is also going to have a new header that we are going to talk about, called Cookie,0571

which is the way of the client sending the cookie back to the user.0580

For example, Set-Cookie is used by the server to send a cookie to the client.0587

Well, any time a client requests a page (for example, if a client has a cookie associated with the host www.educator.com)0591

from that website (here, index.html), it is going to send any cookies it has that are associated with that site back to the server.0601

So, if a cookie had previously been set and stored from Educator.com on this client,0612

the client uses what is known as a Cookie header in its HTTP request, and what it does is provides the name of the cookie and its value.0619

If we go back and look at our script here again, we can see that this is what it looks like when we request a page after we have already received a cookie.0628

In our previous script, setCookieHeader, the HTTP server on our localhost sent us a cookie called example1cookie, and it has the value value.0638

When we go to request another page on this same website (in this case, it's called httpCookieHeader),0652

what we can see is: if we look down at the request information, if we look at the raw HTTP request, there is a Cookie header.0660

And it says example1cookie=value; so what it has done is: because we have gone to that same website,0672

before it sends this request off to the website, our web browser goes and looks to see if it has any cookies stored for localhost.0678

And then, if it does, it goes ahead and sends those cookies along.0685

Well, in this case, we have a cookie called example1cookie, and it sends the value back to the server called value.0687

And one of the things you can do in Firefox is see the different cookies that you have stored.0695

If you go to Firefox menu, and you go to Options, and then you select the Privacy tab, there is a link on the default page here.0700

You can click Remove Individual Cookies, and what this does is shows all of the cookies that you have from all the different sites.0709

So, here you can see all of the different sites that we have visited, that we have received cookies from.0715

That means that, when we have gone to these websites, we have received an HTTP response from the server that had the Set-Cookie header in it.0720

For example, if we search for our localhost, we can see that we have one cookie.0729

The name of the cookie is example1cookie; its content, or the value of the cookie, is value, which is what we had set, to which the cookie's value was set.0735

And so, this shows you information about the particular cookie.0745

How do you set a cookie? Let's say you are writing a script, and you want to send a cookie back to the server.0755

For example, you want to maybe provide a user ID; you can say userID=1001.0762

So, every time the user comes back to the site, it will automatically supply that information to the server via the Cookie header in the HTTP request.0768

Well, PHP provides a built-in function called setCookie.0778

And what that does is allows your script to send a cookie back to a client.0782

One important thing to note is that, because setCookie involves setting an HTTP header (in particular, the Set-Cookie header),0787

you have to call it before any of the script's output is generated.0795

We had seen this before in examples when we used the header method--for example, to redirect the user to another web page.0799

And when we use that before, we have to do that before we generate any output, or else we are going to get an error.0817

So, it is important that you call setCookie before you generate any output for your script.0821

The first two parameters of the setCookie method are the name of the cookie and the value that you want to assign to the cookie.0827

If we go and take a look at a script called setCookie, we can see that it is a PHP script.0834

And before any of our output is generated, we have a PHP section up here that calls the setCookie method.0840

And what it does is: it is setting a cookie called example2cookie, and we are setting the value of that cookie just equal to the string 'value.'0846

So, when the user requests this page, when PHP generates the HTTP response to send back to the client,0855

it is going to generate a Set-Cookie header that is going to contain this cookie.0864

It is going to say "example2cookie=value."0869

And then, it is going to return whatever HTML the page contains, that you are sending back to the user.0872

In this case, it is just some output that shows an example of the headers that you are receiving from the web server.0880

If we go and look at our example2, and we go to setCookie.php, we can see that this is an example of what our response header looks like.0891

So, when we go to this page, we are getting a response that has the header Set-Cookie that says example2cookie=value.0904

If we go down here in our Firebug and we look at our response, and we view the raw HTTP response header,0911

we can see there is, in fact, the Set-Cookie header that shows that a cookie name example2cookie0918

has been sent to the client, and it has the value 'value.'0927

If we go ahead and look again at our cookies for localhost, we should now be able to see that we have two cookies.0931

We have the example1cookie from our previous example and example2cookie from this example.0940

One of the features of cookies is that they have several attributes that you can set.0949

And these attributes determine whether or not a client is going 0953

to send a particular cookie to a web server when it is making an HTTP request for a page.0957

We have already implicitly said that, when a client receives a cookie from a particular website, it stores that cookie.0965

And then, any time it visits a page on that website, what it does is goes ahead and sends that cookie, along with any request that it has.0975

Well, you can explicitly set that; there is a domain attribute that you can set for a cookie that explicitly specifies the domain for which a cookie applies.0985

So, in our case, for example, it has been localhost.0995

We were not explicitly providing that; and what a specification does is: when a browser receives a cookie0997

that doesn't have a domain attribute set, it uses the domain of whatever website it received it from.1003

In our case, when we looked at those cookies in our Firefox web browser's Cookies dialog box,1011

and we searched for localhost, we could see that the domain 1019

associated with those cookies is localhost, because that is where they came from.1022

There is also a path attribute that you can associate with a cookie.1026

And that says, "Within a particular domain, the client is only going to send a cookie back to the browser if it requests a page within a particular path."1030

For example, if we look in a little more detail at the cookie we received on our example number 2,1042

we can see information down here that Firefox provides.1056

It the name of the cookie, example2cookie; it has its content, which is value.1059

We can see it has the host, which is the same thing as domain, and it sets localhost.1063

And we didn't explicitly set that, but that is implicitly set.1067

Additionally, if path is not explicitly set, then it the path of the cookie gets set to whatever path the script that you requested was.1070

In this particular case, the path for our script, setCookie.php, was in the example-2 directory1087

of the lecture_23 directory of the lecture_examples directory in the advanced_php directory.1098

Any time we use localhost, and we access or request a script within this example-2 directory, this example2cookie is going to get passed on.1104

For example, if we refresh this page, because we are still in this example-2 directory, 1117

we are also going to have a request header now that is going to pass that cookie along.1123

Not only does the cookie get set, but also, if we look at our request header, we can see that this example2cookie has been passed along.1129

Now, that is associated with this particular path.1136

Let's say we were to go up one directory, out of the example-2 directory, and we were just to refresh the page,1139

which is just requesting the directory listing for lecture_23.1149

Well, the lecture_23 directory is not lecture_23/example-2, so our web browser should not send that example2cookie in its request for this directory listing.1153

If we go and look down at our request headers, we can see that there is no Cookie header that is sending that along.1166

The other common cookie attribute that is set is called expires.1177

And that is the date and time when a cookie is no longer valid.1181

So, in addition to when a client is requesting a web page, it checks to see if it has any cookies for that particular domain;1184

it checks the path that it is requesting the script from.1192

If a cookie in that domain matches that path, it will send the cookie.1195

And then also, it checks to see if the cookie has not expired.1199

If the cookie has not expired (meaning that the expiration date and time of the cookie has not yet occurred), then it will set the cookie.1201

If the cookie has expired, it doesn't set that.1208

These are three attributes that allow you to determine that, once the server sets a cookie on a client, 1211

when and under what conditions that client will send that cookie back to the server.1222

The setCookie method can take values for all three of these attributes: domain, path, and expires.1228

One thing to note is that the expires parameter takes a UNIX timestamp.1235

However, because in the cookie specification, the expires attribute is a formatted date string 1242

(for example, like Thursday, September 3rd, with a time), you specify a UNIX timestamp, 1248

and PHP automatically converts it to the appropriate timestamp.1253

For example, we have another script called cookieAttributes.php.1259

We are going to create a couple of variables for our setCookie method.1267

We are going to name the cookie example3cookie; we are going to set its value equal to value.1271

We are going to set the domain that the cookie is valid for equal to localhost (even though this is done implicitly, we are just going to do it here explicitly).1276

One thing to note is that the domain always has to be preceded by a dot; that is part of the specification.1283

We are going to specify the path of the cookie; again, this is something that would be implicitly done,1288

but we are going to explicitly specify that this cookie is only valid for the example-3 directory in our lecture_23 directory.1293

We are setting the cookie's expiration equal to time=0; and what that does is: that means that the cookie expires whenever the browser shuts down.1301

That is sort of a default of the cookie specification.1315

Here, we call the setCookie method; we pass it the name and the value of the cookie.1317

We pass it when it expires, and then the path and the domain.1321

And then, this is just an output section that shows what that Set-Cookie header looks like when we receive a response from this page.1327

If we go to example-3, and we go to cookieAttributes.php, we can see here that we are receiving a response1336

that has a Set-Cookie header that has the name of the cookie; 1346

it has the path the cookie is valid for; and it also has the domain that it is valid for.1350

It doesn't have an expires attribute, because it has a default expires attribute, which is whenever the session ends, which is why it was set to 0.1356

If we look down here at our raw HTTP response header, we can see the same information1366

with the path, the domain, and then the cookie name and value specified.1373

Now, one thing that you can do is: let's go ahead and try to explicitly set the time.1378

As mentioned, the setCookie method takes a UNIX timestamp, and then converts it to an appropriate date and time.1383

So, let's say we want this cookie to expire one hour from now.1389

It does things in seconds, so 60 seconds times 60 minutes will be one hour.1394

We save it; now, when we go ahead and reload this page...1400

Well, first of all, let's look at the cookie details for example3cookie.1405

We can see that it has the name example3cookie and the value 'value'; it is for the domain localhost.1417

Its path is for the example-3 directory; and expires--it says at end of session, which is when the browser closes (and that is the default).1423

Well, now we have explicitly set the expires value; so when we refresh this page, we are going to see that, 1432

in our new Set-Cookie header that is generated, now there is an expires attribute1439

that has been set by the server, when it sends the cookie back to the client.1445

And what it does is: it took that UNIX timestamp that we created and went ahead and generated a date/time string.1450

This is what the format of the date/time string looks like.1456

And what it is saying is "an hour from now is when this cookie expires."1458

And if we look at the raw HTTP response header, we can see that it has this Expires header down here, the path attribute, and the domain attribute.1464

Now, when we go and look at the cookies from localhost, and we look at example3cookie,1475

now we can see that this expires attribute has been updated to a specific date and time,1485

which means that any time after 0100 p.m. on September 2nd, this cookie is no longer valid.1490

And so, the browser is not going to send it any time it requests a page on the localhost domain at the path for the example-3 directory.1496

One thing that you can do is: in order to delete a cookie (get rid of it), you simply set the expires date of the cookie to a time in the past.1506

For example, if instead of adding 60 minutes, we subtracted 60 minutes from the time,1515

that is going to set the cookie's time to a time in the past.1520

What is going to happen is: when we refresh our page, you can see that it shows an expires time that is in the past.1522

And when we look at our raw Cookie header, we can see that it sets the expires attribute to a date in the past.1533

Now, because of that, when we go and look at our cookies for localhost, the example3cookie is no longer there.1543

And that is because our browser recognized, when it received the cookie, that the cookie was expired.1553

So, what it did was deleted it.1557

So, that is one thing to note: if you already have a cookie set on your client machine for a particular domain,1561

a particular path, and with a particular name (for example, example3cookie), if you reset that cookie using the Set-Cookie header,1568

as we did here, it overwrites all of those cookie attributes.1576

So, in this case, we are overwriting the value to 'value,' which is the same as before.1580

We are overwriting the path and domain; well, actually, the path and domain will be the same.1585

But what we are doing is overwriting the expires attribute.1590

What that is going to do is change the value of that cookie on the server, and it is going to update 1592

the expires attribute to be in the past, which means that the cookie is no longer going to be set.1596

Now, if we notice, when we refresh this page, even though we had previously set a cookie 1603

for this particular domain and this particular path, we can see, if we look at the raw HTTP request, 1609

that there is no Cookie header, because there is no cookie to pass on, because the cookie had expired.1615

We use these cookies to pass information back and forth between the client and the server.1624

And so, the question now is, "How do we access that information on a PHP script?"1629

We have a client that we have set a cookie for; the client requests a PHP page, and we want to find out some information in the cookie.1634

For example, maybe the cookie contains information a shopping cart, and we want to access that information in our script1640

to find out what items the user already has in their shopping cart.1646

The way you do that is: we are going to introduce another superglobal called _COOKIE.1653

And what that does is: on any script that is loaded, if a Cookie header has been sent by the client in the HTTP request,1658

any cookie name/value pairs that have been sent are going to be created in this _COOKIE superglobal.1669

For example, if a client were to request index.php at localhost, and it were to set the Cookie header,1676

it is going to send a cookie named testCookie, and it is going to have its value equal to cookieValue, 1683

which means that this cookie was previously set for localhost for this particular client.1690

So, it has it stored, and it is sending it back to the server when it is requesting index.php.1695

Well, this index.php page can access this testCookie; it can access the value that it was set to, using the _COOKIE superglobal.1702

And the _COOKIE superglobal is an associative array that contains the names of all of the cookies that were sent to a particular script by the client.1710

In this case, we have one cookie, testCookie; and then, the value of it is the value of this cookie.1721

cookieValue here is going to be equal to the string 'cookieValue.'1727

One of the things we could have done here instead: we could have said item-1001 equals 2.1735

And we will say that that cookie represents that we have item 1001 in quantity 2 in our shopping cart.1742

Now, we could say quantity(Item) equals...and what that is going to do is look for a cookie1749

named 1001 (in this case, assuming we pass it along, it is going to say 1001).1769

And then, it is going to load that value, which is going to be equal to 2.1774

And so now, we are going to know the quantity of that item in a particular cart.1778

If we look at our file called cookieSuperglobal, here we have our same setup here at the beginning,1787

where we are setting a cookie in this particular page.1793

And then, we are outputting information about the HTTP response that is generated, 1797

which outputs the Set-Cookie header, so that we can see what it looks like.1803

Then also, we have a section that is going to try and access the value of this cookie.1809

And what it is going to do is: we named our cookie, in this case, example4cookie; and then, we are going to try to output the value of it.1813

What we do is: if we go to example-4, and we load our page cookieSuperglobal.php,1821

we can see that a cookie was set with the value sampleValue; it is called example4cookie.1835

However, in our script, when we try to access example4cookie, it is nonexistent.1842

Now, the reason for that is that the _COOKIE superglobal only has access to cookies that were sent as part of a request for a particular script.1847

The first time, when we requested this particular script, cookieSuperglobal.php, we had no example for cookie.1858

It hadn't been set yet, so we had nothing to send back to the client.1866

If you look at our request and response when we requested this page, you can look at the requests,1869

and you can see that there is no cookie here, because we had not received a cookie yet.1875

However, in our response, we can see that a cookie was set, example4cookie; and it has the path and the domain for it.1879

So now that we have received this cookie, the next time that we refresh this page, we are going to send that cookie along,1887

because it is associated with that path and that domain.1893

And then, we are going to be able to access it in our script.1898

For example, if we refresh the page, now we have access to the value of that cookie.1901

The reason is that, because we had already received the cookie, when we re-requested the page, we send that cookie along.1906

And if we look at the second time we requested that page, we can see that we passed this cookie along via the Cookie header.1913

And one of the things that you can do is set multiple cookies for a particular page.1922

For example, we could set another cookie, call the cookie hello, and set its value equal to world,1927

and just have it have default values for domain, path, and expires.1937

Now, we are setting two cookies when we go to this page.1942

And then, instead of just outputting our cookie example4cookie value, let's go ahead and...1946

we'll just print out the entire _COOKIE superglobal, which will provide information about both the cookies.1957

So now, what we do is: when we go and reload this page, we can see that it has access to our example4cookie.1975

However, we can see that the cookies array only has example4cookie.1989

That is because this page, when we reloaded it for the first time, sent that cookie back to the user.1993

So, the first time we load that page, that second cookie is not available to be sent back.1999

And if we look at our HTTP header, we can see that, in our Set-Cookie header, we have two cookies that are sent:2003

example4cookie equals sampleValue, and then also our other cookie that we created, called hello=world.2017

And when we requested this page, we only had the example4cookie; that is all we sent back.2024

If we go ahead and refresh this page, and look at our HTTP request, now we can see that it sends both cookies back.2029

And one thing to note is that when a client sends a cookie via a Cookie header back to the web server by an HTTP request,2037

it only sends the name and value of the cookie; it doesn't send the expires attribute or the domain attribute or the path attribute--2047

whereas, when the cookie is set, the server does send that information.2057

The reason is that that information is used by the client to decide whether to send the cookie back; and the server does not need to know about that.2060

So, now, when we look at the output of this script, when we dump our _COOKIE superglobal, we can see that it has two cookies in it.2067

One is example4cookie with value sampleValue, and one is the hello cookie that has the value world.2076

I just want to talk, really quickly, about security implications of cookies.2086

Cookies can be essentially be used to track users, and so they have some privacy issues associated with them.2090

For example, let's say you go to a website, and your browser is allowed to accept cookies.2095

They (the website) can set a cookie that sends a unique user ID.2100

So, every time you go back to that website, your browser is going to match the domain of that website, and it is going to send that cookie.2105

So, in that way, the website can track how many times you go to the site, and so forth.2111

There are also some security issues with cookies, in that they store information.2117

So, you could have some sensitive information that gets stored on a person's computer,2121

so anybody that has access to that computer could look at that information.2125

For these reasons, you may have heard that users can disable cookies, which means that they don't accept cookies from web servers.2128

The reason I am mentioning that is that it has the implication that, if you are planning on using cookies2138

to enable some functionality of your website, you have to consider the fact that2144

some of your users may have cookies disabled, and therefore may not be able to access any cookie-dependent functionality.2148

That is just something you should consider.2155

Most people typically use cookies; most websites use them; but that is one thing to consider,2156

depending on your user base and your application, as to whether or not to use cookies--2163

because some of your users may not be able to have access to them.2167

For our homework challenge, I want you to create a script in a directory call subdir in the lecture_23 directory.2172

So, it is a subdirectory; it uses the Set-Cookie function to set a cookie named userID with the value 100.2183

And then, in the same script, I want you to use the _COOKIE superglobal to output the value of that cookie.2191

And remember that the first time you browse to that page, even though you have set the cookie, you are not going to be able to see it,2197

because when you request the page for the first time, you are receiving the cookie for the first time.2203

So, you don't have that cookie to be able to send back.2207

When you refresh the page, you will be able to see the output of that cookie.2209

One thing to note is that you make sure that you call your setCookie function before you try to output the value of the cookie,2213

because setCookie affects HTTP headers, and it has to be called first.2219

Otherwise, it will generate an error.2222

Then, in that same directory, create a second script that deletes the userID cookie.2225

And the way it does that is: you are going to set the expires attribute for that cookie in the setCookie method to a time in the past.2231

And what that is going to is delete the cookie.2238

When you run the second script, it is going to delete that cookie, and you then go ahead and reload (in step 4) that first script again.2241

You should, again, see that the value of the cookie is not available for output.2248

The reason is that the second script deleted that cookie, so when you go back to that first script, you have no cookie to send to the browser.2252

If you go ahead and refresh that page again, however, because that first script sets the cookie,2258

the second time you load it, the value of the cookie is going to be able to be output.2264

Then, going up one directory in lecture_23, I want you to create a script that tries to output the value of the userID cookie, using our _COOKIE superglobal.2269

And when you try to load a script, you should notice that, again, the cookie's value is not output.2281

In this case, it is not because the cookie doesn't exist.2287

It is because, as we mentioned implicitly, when you create a cookie, if you don't explicitly set a path or domain,2290

the cookie's path and domain is the path and domain of whatever script set that particular cookie.2296

So, in this case, because the cookie we generated before was associated with the path lecture_23/subdir,2304

when we are just in the lecture_23 directory, this cookie that we had set doesn't apply, because the path doesn't match.2314

So, it is not going to send that cookie; because it doesn't send that cookie, you are not going to be able 2323

to access it via the _COOKIE superglobal, and you are not going to be able to output its value.2326

And so, that shows you a little bit about how the path attribute works for cookies.2332

One thing to note is: practice using the Firebug add-on, when you are running these scripts,2338

to take a look at the raw HTTP request and response headers.2344

That will allow you to look at the Set-Cookie and Cookie headers to see what is going on behind the scenes,2347

so you can understand how those headers work, and how the different cookie attributes (such as expires, domain, and path) are set.2353

It also allows you to see when a cookie is sent from the client to the server, and when the cookie is set in an HTTP response from the server to the client.2361

And that will give you more practice in understanding how cookies work, and when and why2372

they are sent back and forth between a server and a client.2378

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2383

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0002

In today's lesson, we are going to be continuing development of our web application.0007

We are going to be incorporating what we learned in our last lesson about cookies to improve the functionality of our site's shopping cart.0011

We are going to introduce a couple of small topics before we get into the actual changes we made to the web application.0019

We are going to be talking about a new operator called the instanceOf operator.0026

And then, we are also going to be talking about how to access properties of objects that are properties of other objects.0031

And we will see a little more about what that looks like on the slide coming up.0038

Then, we are going to go through two different versions of the web application.0042

In version 11.0, what we are going to be doing is creating a shopping cart object.0045

It is going to be called a Cart--that is the name of the class.0051

And we are going to use that to represent our shopping cart.0056

Right now, we have been using an associative array that we have been passing around,0059

called items, that has keys that are the item ID of the item in the shopping cart, and then its value is the quantity.0064

Well, we are going to change that and put it into an object.0074

In 11.1, what we are going to do is implement a shopping cart that uses cookies.0078

So, in 11.0, we are going to convert things over to an object model for our shopping cart; in 11.1, we are going to 0084

use that object model with cookies to get a more functional shopping cart.0090

PHP provides what is called the instanceOf operator, and what it allows you to do is determine whether a variable is an instance of a specific class type.0096

For example, if we have a variable called object, or obj, and we want to test 0107

to see if it is, for example, an instance of the Item class that we use in our web application;0113

The way you would do that is: instanceOf is a binary operator; you put the variable that you are testing the type of on the left-hand side.0119

And then, you put the exact name of the class on the right-hand side of the operator, and this becomes a boolean expression.0127

So, what it does is says, "If object is an instance of the Item class, return true; if it's not, return false."0134

isItem would be true if object is an Item, and it would be false if it isn't.0142

This is useful for when you are accepting parameters from functions and so forth,0146

to test and make sure that you are getting appropriate objects that you might be working on.0151

For example, if you need an Item object to work on, you need to be sure that you are passed an Item object, as opposed to an Integer, for example.0156

And again, you need to make sure that you use the exact name of the class to the right of the operator.0164

And it is just the name of the class; there is no dollar sign or anything like that.0169

Also, we know that an object has properties.0175

And the data types of an object's properties can be any data type, which includes other objects.0178

So, for example, we could have a Cart class, and we could define a variable item that is intended to be a variable that represents an Item object.0185

What we have is an object within an object; so how do we access the properties of the Item object that is a part of the Cart object?0206

Well, we use the arrow operator and a cascaded syntax.0214

Let's say, for example, we have a Cart class, like the one above, that has a property named Item, as it does up here,0219

which is an Item object; that is the data type of that property.0226

And let's assume that the Item object is the Item that we use in our web application.0231

So, the Item object, we know, has a price property. How do we access the price property?0235

Let's say we have an instance of the Cart class; we have created an instance of Cart called cart.0242

Let's not worry about the details behind it.0248

But it has been set up; an item has been added to it, so the item has been set to a new Item object, for example--maybe in the constructor of the cart.0249

And we want to access the price of this particular Item object.0260

Well, the way you do that is using multiple arrow operators.0264

For example, we get the instance of our Cart object, and then we use the arrow operator to say, "Give me the item property."0268

And what that is going to do is return the instance of the Item object that this current instance of the Cart item property is set to.0277

And then, now that this is an object, we can again call the arrow operator on it to say, "Now I want the price property of this object."0288

In this case, this is an Item object that was taken from the Cart object; and so, this is saying how to get the price from it.0297

And you can do this indefinitely; you can have objects within objects within objects.0304

And the reason I am introducing in now, as well as the instanceOf operator, is because these are some things0309

that are getting introduced into the versions of the web application we are going over in today's lesson.0314

So, let's say Price was even an object, and maybe it had a property that was called currency, that lets you know the currency it was in.0320

And we could access it like so, and that goes on down the line.0330

This also works with class properties that are arrays of objects.0336

For example, let's say, in our cart, instead of just having an Item object, we had an associative array of Item objects,0341

where the key to that array is an item ID, and then the values are Item objects.0348

What you can do is say, "For this Cart instance, give me the Item object that is in the items associative array, associated with the key item-1001."0357

This is going to return an Item object, and then because it is an object, we can use the arrow operator on it to get the price of it.0369

And so, this is going to say, "Give me the price of this Item object."0378

This is saying, "Get me the price of item-1001 that is in this particular Cart instance."0382

This would be assuming that it has an item 1001, and so forth.0390

But that just demonstrates how you can also access object properties that are arrays of objects.0393

Now, we are going to get into the nuts and bolts of the changes we are making in this web application.0403

We are introducing two new objects into our web application: Cart, and one called CartItem.0408

And what they are is classes that are created to model a shopping cart.0415

That is what we do with object-oriented programming; we model real-world objects.0419

We have a Cart class, and as in the last slide's example, it is going to contain a property called cartItems.0425

And this cartItems is going to be an associative array of CartItem objects.0445

So, we have another object that we are creating called CartItem.0452

And what this does is represents an item that is in a cart.0457

We set it up so that it has two properties: one is called item, and one is called quantity.0464

For example, in our shopping cart, when we add an item to a shopping cart, we add the item, and then we also have a quantity associated with it.0471

We are going to encapsulate that into one object.0478

It is a CartItem object; it is going to contain an Item object, which is the store item that this CartItem represents.0481

And then, it is also going to have an Integer property, quantity, that is going to represent what quantity of that item is currently in the shopping cart.0488

Now, in our shopping cart, this is an associative array; it is going to have keys that are item ID's for items in the shopping cart.0496

And what they are going to point to is CartItem objects, which, as mentioned over here, contain an Item and a quantity.0504

We have this Cart object that contains an associative array of a number of CartItems.0519

And a CartItem is an object that encapsulates a store item, along with its associated quantity.0525

What we can do, then, is: we are also going to be creating a method for our CartItem class called calcItemTotal.0532

What that is going to allow us to do is: because this CartItem class knows what Item it represents, and it knows the quantity,0544

it has access to the price of the Item; it also has access to the quantity of the Item.0553

So, we can calculate the cost due to this particular Item in the Cart.0557

And that would be the price of the Item, times whatever quantity it is in.0562

So, what we can do in our Cart class is: we are going to create a method called calcTotal.0566

And what that is going to do is loop over, when we need to calculate the total of a shopping cart, all of the CartItem objects within its cartItems array.0573

And it is going to call the calcItemTotal on each of those items.0584

Instead of having to manually go and look up the item and get its price, and then multiply it times the quantity,0588

it is going to have the CartItem object do it for us by this calcItemTotal method.0595

This is going to loop over all of the different CartItem objects within the cart.0600

It is going to add up their totals, multiply it times the sales tax rate, and then generate the total for the entire cart.0604

So, each CartItem generates the total due to that item, and then the Cart takes all of those CartItem objects together,0614

adds them up, and then calculates sales tax.0622

So, we are going to be replacing our former method (that was just a user-defined function called calcCartTotal).0624

And that functionality is going to be moved into this Cart class, as well as this CartItem class.0633

Let's go and take a look at what these classes look like.0640

Look at version 11.0...well, first let's look at the CartItem.0645

Our CartItem class, if we look at the source code, has two properties: item and quantity.0655

quantity is an integer representing the amount of this particular item in the cart.0663

item is an Item object that represents the actual store item that this CartItem represents.0667

This object is an Item and its associated quantity.0674

We have a constructor that takes an Item object and an integer for the quantity, and just sets those private properties.0680

And then, here is our calcItemTotal method that we had talked about.0687

What that does is returns the total due to this particular item in a particular shopping cart.0692

For example, it multiplies the item price times its quantity.0698

Well, it gets the quantity from this CartItems variable quantity; so it says $this and then gets the quantity.0701

Now, to get the price, the price of an item is contained within the Item object;0710

so what we need to do is use the $this variable to say, "Give me the Item property of this particular instance of a CartItem."0715

And what that is going to do is give you the Item object of this item property that was set in our constructor.0723

And then, using this cascaded arrow syntax that we talked about before, it is going to say, 0730

"From that Item object that this CartItem represents, give me the price of that."0735

It is going to multiply the two together, and it is going to return that.0740

If we go and look at our Cart class, it has a number of different methods in it.0744

It has a constructor that, as we will see, allows you to pass it a bunch of items--not CartItems, but Item objects.0747

And it will add them to its cartItems property.0756

So, let's look at the source code; we can see that it has one property called cartItems, as we had discussed.0761

And it is an associative array of CartItem objects, and the keys to that array are the item ID's.0768

Now, this Cart class has a number of different methods that have been created.0774

It has an addItem method, which allows you to add an item to a particular cart.0779

It allows you to get access to that cartItems property, which gives you an associative array0785

of all of the CartItem objects contained in this particular shopping cart.0792

It has a method called inCart that allows you to test whether a particular item is currently in the cart, based on item ID.0797

It allows you to test whether the cart is currently empty or not (meaning that there are no items in the cart).0803

And then, it also allows you to remove an item from the cart by specifying the item ID of the item you want to remove from the cart.0809

And then, here, our calcTotal method, if we look at the code for it--we can see that what it does is:0816

it gets the associative array property in this class cartItems, which is an array of all of those CartItem objects.0824

It loops over each of those items, and then it cumulatively adds to the subtotal the total due to each item.0831

So, for each CartItem object it loops over, it calls the calcItemTotal method and adds it to the subtotal.0838

Once it is done looping over all of the items, it adds the sales tax to it, rounds it, and then returns that method.0843

And that is going to be used by, for example, our checkout script, to be able to calculate the total of a cart.0849

One thing to note is that, if we look at the addItem function, what it takes is not a CartItem object, but an Item object.0861

For example, when we go to add an item on our script--let's say we are going to be adding a button to our item.php page0870

that is going to allow you to add an item to the cart--when you click on that item, it is going to go to viewCart.php.0879

And it is going to load an Item object from the database for the item that you selected, based on the item ID.0884

And then, it is going to be calling this addItem method on a shopping Cart object, and it is going to pass it this Item object.0893

Well, what is going to happen is: this method is going to test if this item is in the cart.0901

If it is not in the cart, it is going to create a new CartItem object that wraps that particular Item object.0907

And it is going to set its quantity equal to 1.0912

If it is already in the cart, what it does is goes and gets the current quantity of that item in the cart.0915

And in this case, you can see here: we are using the syntax again--the cascading arrow syntax.0922

And here, what we are doing is saying, "From this particular Cart object, give me the cartItems property (which is an array)."0927

"Give me the CartItem object that is associated with the item ID that is for this Item we are trying to add."0934

"And then, get me the quantity of it."0944

And then, what we are going to do is re-add the item to the cartItems array, but increasing the quantity by 1.0945

And so, that is how we add the item to the cart.0953

What we have done in our web application is (let's reduce the size of this a little bit): in version 10.1,0961

which is our last version of the web application, when we go to viewCart, what it does is simply outputs all of the items in a particular store.0972

And that is not typically how a shopping cart works.0983

Typically, you have an empty shopping cart, and as you add items to it, it builds it up.0985

Because we haven't had the functionality to be able to do that, our last version of it just lists all of the different items.0989

And you enter the quantity you want, and then you go to check out.0995

And there, it is going to say we need to add something.0999

In our new version, what we have done is: on each item page, we have added a button here called Add to Cart.1003

If we look at our old version, there is no button.1011

And what that does is: now, when we click on Add to Cart, it is going to go to the (I'm not sure why the lines aren't showing up; 1014

there they go) viewCart page, and it is only going to add that item to our shopping cart.1025

So, now our viewCart page only has the items that are in the particular shopping cart.1030

What we have done is modified our viewCart script.1037

So, now viewCart, instead of just being, in a way, a static script that just goes through and lists (in our old version)1039

all of the different items in our particular cart, what we are going to do is pass to it an action.1048

And we can set the action to be addItem, and then we specify the item ID of the item we want to add to the cart.1055

And then, we are going to look at viewCart in a second, and we are going to see how we process that into adding an item to a cart.1061

We also can remove an item from the cart, and that is a feature that we have added to the page--we have added this Remove link.1068

And what that does is: now our viewCart page can also process a removeItem action.1075

And you specify the item ID of the item that you want to remove.1083

For example, let's go look at viewCart.php.1089

Previously, in 10.1, all we did was got all of the items in the store, using this getItems user-define function.1094

And then, we just output a row in the table for each item in the store.1104

Now, in our viewCart class, what we have done is: we allow it to take an action now, and an item ID.1109

And the item ID is going to be the item that we want to add or remove from the cart.1119

And then, in our data processing section (and this is just temporary, for this version of the app;1123

and we are going to update it later in this lesson to use cookies), we are going to create a Cart object.1128

And then, what we are going to do is: if the action of the script is to add an item, we are going to load the Item object1136

from the database, based on the item ID, and we are going to add it to the cart.1144

If it is to remove the item, we are going to use the removeItem function that we created in our Cart object to remove the item from the cart.1148

Then, we have changed the output of our Cart page.1159

Before, we would just output rows for each item that is in the store.1165

Now, what we have done is: because we have this isEmpty method, we first of all test if the cart is empty.1171

If it is empty, we just output a message that says, "Your cart is empty," and the script is done.1177

If not, what we do is output that table again.1182

But this time, we loop over all of the items that are currently in that Cart object.1186

So now, instead of just looping over all of the items in the store, we are only looping over all of the items that are in the cart.1191

When we add an item to the cart, the cart is going to be populated with an item.1196

When we call getCartItems on that object, we are going to get the associative array that contains all of those CartItem objects.1200

And then, what we are going to do is extract information from that CartItem object to output each item that we have in our shopping cart.1206

It is going to output the item's name, a link to the item's page, its price, and its quantity.1215

And then, also, we have added this new link down here, which is a link to viewCart.php1221

that has a query string that says Remove Item, and it provides the item ID of the item we want to remove.1227

And so, what that is going to do is do that for each item in our particular cart.1235

The thing that you will notice is that, in our new version, if we added Baseball Bat to the cart;1239

well, if we go and look at our viewCart script at the very beginning, we are going to see that it is going to create a new Cart object.1249

It is going to add the item to the cart, and then, when it goes down to the processing section,1256

it is going to be able to loop over that one CartItem and output a link for it.1262

So, as you can see, it is output here.1267

Now, however, if we go ahead and click viewCart again, and this time just go to viewCart 1270

without any action that says Add Item, it is going to say the cart is empty.1279

And what has happened is that we lost the state of our shopping cart.1282

And that is what we are going to learn that cookies are going to provide for us.1286

They are going to allow us, in between viewing different pages of our website, to maintain the state of that shopping cart--1288

to say, "Hey, this item is in the cart, and it has a quantity of 1."1293

The reason is that, when we go to viewCart without any Add Item action,1296

when we go up here, it is going to create a new Cart object; but it is going to have no item to add to it.1304

So, our cart is going to be empty, so when it goes down here, it is going to say, "Cart is empty," and it is going to output, "Your shopping cart is empty."1307

We have no way, right now, of showing that when we go from viewCart to viewing the cart over and over again--1314

we have no way for those different HTTP requests to maintain the state of the cart.1322

And we are going to do that, using cookies.1328

The other thing that you will notice, as a result of that, is: let's say we add a basketball to our cart, 1330

so now we have a basketball in our shopping cart; now, let's say that we want to go and add a DVD player.1336

Well, when we add a DVD player to our cart, we can see that the basketball is no longer in there.1342

Again, that is because we have no way of maintaining state between the different requests.1348

Each time we go to this viewCart page, it doesn't have any prior knowledge about the basketball that we have added.1353

All it knows about is the item that was currently added to the cart (in this case, it added item 1005).1360

And we are going to see how to fix that in our new application, with the use of cookies.1367

And so, as mentioned, you can see that we have added the Add to Cart buttons to our Item page.1374

And we have added Remove links to remove items from the cart.1380

One other thing is that we have also updated our checkout.php.1385

Previously, in checkout.php, what we would do is pass an items array via POST form.1392

For example, when we would submit this form on our old application, it would post (let's show an example) data to checkout.php.1399

And if we look at the POST data, we can see that it has this items array1416

that has a key which is the item ID, and then the quantity associated with each item.1421

For example, this shopping cart contains items 1001, 1002, and 1003.1427

It contains quantity 1; and so, that is how we are able to calculate our shopping cart total.1431

What we are doing is passing the information along in this array.1437

Well, in our new version, we don't have that form anymore to submit.1444

All we have is this Add to Cart button, and what that does is passes information to the viewCart page, using the action and itemID.1448

And so, what that does is: our viewCart page now only has one item.1461

So, when we go to check out, as you are going to see (and I will explain in a second why that doesn't work),1464

what is going to happen is: we are not submitting all of that information anymore.1471

We are not submitting this items associative array that contains all of the items in the store, along with their quantities.1474

Instead, what we are going to do is change checkout, so that it is going to be able to use a Cart object.1480

What is eventually going to happen is: we are going to have a cookie that is going to contain all of our shopping cart information.1486

So, when we click checkout on our viewCart form, it is going to go to the checkout page.1492

checkout.php is going to be able to read the cookie, build up a Cart object, and then be able to process the order--1498

for example, to send out an email that says, "OK, this is the order that was emailed."1504

We don't have that functionality with the cookie set up right now, so what we are temporarily doing is:1509

we have no way of passing the information from our viewCart form to our checkout.php,1513

because in our new version, viewCart.php is no longer a form.1518

It is just a link to checkout that says "action=checkout."1523

What we do is: just so we have something to show for this checkout form, we create a fake cart.1528

We are just creating a Cart object, and we are adding two items to it.1534

And then, what we are doing is: we just check to make sure that the cart is not empty, which it is not going to be, because we have added stuff to it.1539

We calculate the cart total using the calcTotal method.1544

And then, we process things as before; if the action is to complete the order, we validate the customer data,1550

and then we go ahead and email the order to the site administrator.1558

One thing to note, among many things to note, is that previously we validated the cart by using this isValidCart function that was in our utilLIB.1564

We are not going to use that anymore, because now we have this isEmpty function that is built into our Cart object1575

that will automatically tell us whether the cart is empty or not.1581

We are not going to be using calcCartTotal, because that functionality is now built into our Cart object.1583

And then, in addition, as we saw in our emailOrder function in our last version,1591

we provided it this cartItems associative array, which is that array that has keys of the items' ID's and the values of the quantity of each item.1598

We pass it the order total that was calculated by the calcCartTotal function up here.1607

We pass it the array of customer information.1617

And then, we also have to pass it information about all of the items in the database,1619

because emailOrder needs to extract the price information from the items, for example.1623

It needs the item information, so we have to pass all of that.1628

Well, in our new call to emailOrder, we only pass it two pieces of information.1633

We still pass it the customer data that was submitted on the customer form.1638

But we also now just provide one other variable called Cart, which is this Cart object that we have created up here at the beginning of the form.1642

Now, because the Cart object contains CartItem objects that have their quantity, and then it also has 1651

the Item object embedded within it, that emailOrder function has all the information it needs, within that Cart object,1656

to be able to extract the price of each item, and to generate the order for the particular email.1663

If we look at our emailOrder function, we can see that now it takes a Cart object that contains all of the contents of the shopping cart.1670

And then, it still takes a Customer object that contains all of the customer data.1689

And we can see that what it does here is: now, it loops over each of the items that are contained in the cart.1694

It extracts the price information, and then the quantity information, and then outputs a line in our email--1700

whereas, in our previous version of this, it was a lot more involved in our emailOrder function.1707

What we had to do was loop over each item ID in our associative array and get the quantity for it.1716

Then, what we would have to do, if the quantity was greater than 0, would be to look up the Item 1724

from the parameter allItems that was passed, which is a listing of all the items in the store,1737

extract the price information that way, and then generate this line that shows the item ID and its price.1743

Now, we extract all of that information, rather from this allItems array (that contains information about all the items in the cart),1750

simply by accessing the information that is in the cart method.1757

And so, we have used the emailOrder function.1765

The other thing is that, in our checkout.php script, previously, when we...1767

checkout.php has two sections to it: it previously received information from viewCart.php...1775

And that information would contain all of the item ID's and their quantities for items in the shopping cart.1781

And then, what it would do is allow the user to enter shipping information.1788

And then, it would proceed to a Complete Order section.1793

So, it has two actions that are processed.1797

Well, in order to be able to access all of that cart information that was passed from viewCart.php to checkout.php the first time,1800

what we had to do at the bottom of our form for the customer information was:1809

we had to loop over all of the items in the cart, and create hidden input fields 1816

that would create that items array that specifies the item ID and the item quantity.1821

Well, we don't need to do that anymore, because what we are going to be doing in the next version is using cookies to contain all of that information.1828

So, we have eliminated that from our checkout.php.1834

We have also eliminated passing along the order total between the different actions of our checkout.php form,1839

because now, each time checkout.php is loaded, it has access to the Cart object, which can calculate the total each time.1845

So, we don't need to pass that along.1852

So, when we look at checkout.php in our form, we don't have any of that information here at the bottom.1854

Now, we are going to get to the point where we use cookies.1864

What we are doing is: we are going to use cookies to allow us to maintain state between adding different items to the shopping cart,1867

and also to be able to pass that information from viewCart.php to checkout.1874

We have created a user-defined function in our util library called buildCartFromCookies.1878

And what that does is: it is going to, when you go to the checkout form, for example (checkout.php),1885

look at the cookie that the user sends; it is going to see all of the information in that cookie.1892

And then, it is going to build up a Cart object from that cookie.1897

The cookies that get set when you add an item to the cart are simply going to be name/value pairs1900

where the name is the item ID and the value is the quantity.1911

For example, these would be two cookies: one cookie called 1001 that has a quantity equal to 1; and one cookie called 1002 that has a quantity 2.1916

This buildCartFromCookies method would be able to read both of these cookies, and then build a Cart object up1924

that says, "OK, this cart is going to contain the item 1001 (with the quantity 1) and the item 1002 (with the quantity 2)."1929

So then, when you go to checkout.php, it can pass that information along.1938

And then, when you enter your shipping information on checkout.php, instead of having to forward all of that information1942

hidden at the bottom of the form, that cookie is going to get passed along when you go to the completeOrder action of checkout.php.1948

Because it does that implicitly, you don't have to pass that information along.1957

checkout.php will have access to that cookie, and can then get access to all of the cart information.1962

Let's go take a look at what the last version of the store looks like.1967

So now, let's add an item to a cart; we have added a DVD player to a cart.1972

And let's say we want to add another item to a cart--we want to add a basketball.1979

Now, when we add the item to the cart, it actually maintains state.1983

The reason is that, if we look at our new viewCart.php page, what it does is checks to see if there is any cookie data.1988

If there is, it builds a cart up from that cookie; if there is not, it checks to see if the action of the form was addItem.2002

If the action of the form is addItem, and the cart is empty, then what it does is sets a cookie for that new item.2008

It sets a cookie that says, "OK, item 1001 has a quantity 1."2016

So then, now, the cookie contains information that there is item 1001 of quantity 1 within the shopping cart.2021

When we go to a different page and add another item to the store, this cookie that we have previously set here2028

is going to get sent back to viewCart.php.2034

So, when it builds this cart up from cookies again, it is going to know about that previously added item.2037

And so, what it can do is: then, it will maintain that state.2044

And so, it will contain information about the previously added cart.2049

The other thing it can do is: if the item is already in the cart (for example, Basketball), and we want to add another one to the cart,2051

we click Add to Cart again, and we can see, the quantity is updated to 2.2058

The way that works is that, if the item is already in the cart (and viewCart.php will know that, 2061

because it has built up the Cart object from all the cookies that were passed to it), it can check if the item is in the cart.2070

If it is, it gets its current quantity, and then it resets the cookie for that item ID, incrementing the quantity by 1.2076

The same thing works for removeItem, except that it simply sets the time for a particular ID's cookie to a time in the past.2083

That removes that item cookie, and so, the next time you go to viewCart.php, that cookie is not going to get passed along, because it no longer exists.2094

One thing to note is that, on each of these pages, after we set the cookie,2104

that cookie does not become immediately available to the form,2109

because what we have done is built our item up from the cookie that was passed to the form originally,2113

which--if we had no items in the cart--there is going to be no cookie data.2120

When we go ahead and set the cookie, it doesn't know about that cookie until you refresh the page,2126

so we have a header function that refreshes the viewCart.php, which is going to allow it to show the updated shopping cart.2130

And that is why, when we go here, we can see that we have had an updated quantity.2139

Here, we can click on removeItem; what that is going to do...2144

And if you look down here at our Firebug console, we can see that, when we loaded this form,2147

it set a cookie for our Basketball, item 1006; and you can see that it set its quantity equal to 2.2160

You can also see that previously, when we went to this page, the web browser passed along information 2169

about the current shopping cart in the form of a cookie, where it said, "item-1005 cookie is equal to 1; item-1006 cookie is equal to 1."2177

That is how it knew that there was already one in there.2186

What is going to happen is: when you go to this page, you have added a second basketball, for example.2188

It is going to set the 1006 cookie equal to 2.2193

When we refresh the page, you can see here: Firebug lets you see the refresh happening.2196

We can see that, when the page is refreshed, the new cookie has been sent, so it has that item 1005 equals 1 and item 1006 equals 2.2204

And so, that way, when it refreshes, it is able to show quantity 2 for the basketball and quantity 1 for the DVD player.2214

Now, when we remove this, what we can see in our original request is that we set a cookie, 1005,2222

and we have set it to expire in the past, so the cookie is going to be deleted.2234

So, when the page refreshes, we can see that the only cookie it has is for item 1006, which is our basketball.2238

And that is why it doesn't show up again.2245

Now, what we have also done is: on this page, we have a Checkout button that simply goes to checkout.php with the action checkout.2249

And what that does is: because this is in the same domain, it passes that cookie that contains all the information about the cart along.2258

So, checkout.php now is able to build that cart up from the cookie that it has.2264

It is able to test if the cart is not empty.2272

If it is not empty, it can calculate its total.2275

If it is completing the order, then it goes ahead and processes the customer information, and it goes ahead and emails out the order.2278

And then also, what it does is: after it is done completing the order, it goes ahead 2289

and deletes all the different cookies by setting their values to a time in the past.2293

So, after we check out (I'll just put in some fake data here and go to Complete Order), we are going say that the order was successfully completed.2297

But now, when we go back to view our cart, it is going to say it is empty, because all of the cookies have been deleted that had that shopping cart data.2312

The other thing to note is that, when we have that the action is equal to checkout,2322

we are simply outputting the current total, and then we output that shipping table.2328

And again, you will notice, at the bottom here, that it doesn't contain the information 2332

to forward all of the items along to checkout.php with the completeOrder action.2335

And that is because all of that information is contained in the cookie.2341

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2347

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be introducing the concept of sessions.0005

In particular, we are going to be going over what a session is.0010

And then, we are going to talk about two different ways that you can manage sessions.0013

One is a client-side session; one is a server-side session.0017

Then, we are going to talk about how to implement sessions in PHP (which is a type of server-side session).0021

And that is going to involve a discussion on what a session ID is, how sessions work in PHP, a couple of methods,0028

and a new superglobal we are going to introduce that allows you to work with sessions in PHP.0036

And then, we are going to talk about how to access and delete data within a session, which is the state of a particular session.0041

And then also, we are going to finish up with some comments on how to configure sessions in PHP.0048

First, what is a session? Well, on the Web, a session refers to a series of related communications between a web client and a web server.0055

For example, when you log into a website (for example, amazon.com®) and go shopping, and you have your shopping cart,0065

when you add an item to your cart, and you go to the next page, and you add another item to your cart,0073

each of those separate HTTP requests, or transactions, are linked together.0078

The website knows that, when you add an item to your cart, and you go to the next page 0085

and add another item to the cart, both items will be in the cart.0089

It links those together, and it does so over a specific period of time, as well (which is another key element).0093

Sessions are defined both by the two parties communicating (a session occurs 0100

between a particular web client and a particular web server), as well as a time period.0107

Sessions are time-relevant: for example, maybe you have a banking website that you have gone to, and it will give you a warning,0113

after ten minutes, that your session is about to time out.0117

What that means is that sessions have a temporal element to them, and they are confined 0121

to not only communication between two parties, but also communication between two parties over a certain amount of time.0126

Now, that time could be something that times out, and a session automatically ends;0132

or it could be something that...a session can be explicitly ended, either by a server or a client.0138

Sessions are used to link multiple HTTP transactions.0144

An example of that would be when you log into a website with your username, 0149

and then each page you go to on the website might say "Hello, Matthew," for example, at the top of the page.0152

It knows that you have logged in, and that your name is Matthew.0157

And so, every time you view a new page, it is linking those HTTP requests and responses together0161

to know that they are all part of a single session.0167

Additionally, sessions are used to preserve data over multiple transactions.0170

A perfect example of that is a shopping cart: when you add multiple items to a shopping cart,0175

you might do so on two or three different PHP pages, for example.0180

Well, when you finally go to view the cart to checkout (let's say you added three items to your shopping cart),0185

in order to keep track of all of that, that state has to be kept somewhere.0192

The session has to know that you have added, maybe, item 1001, 1002, and 1003, to your shopping cart.0198

Because HTTP, as we learned in our lesson on cookies, is a stateless protocol, it doesn't know,0204

between one HTTP request and the next, about any other HTTP requests; we have to maintain that state somewhere.0211

Data, or state that is preserved between a series of these HTTP transactions 0220

(for example, adding multiple items to your shopping cart) will be referred to as session data.0226

Now, what you may have realized in just that short description of sessions is that we have actually already been implementing a type of session.0233

We have been implementing a client-side session.0239

And we have done that in our web store application, where we used cookies to track the status, or the state, of a particular shopping cart.0244

Every time a user added a new item to their shopping cart, we would set another cookie0254

with an item that has the cookie's name as the item ID, and then set its value equal to the quantity added.0258

And we would update, add and delete, and move these cookies in order to maintain the state of the shopping cart.0264

This is called a client-side session, because the state data, or the session data, is stored on the client.0270

In this case, it is stored in the form of cookies, which, as we know, are name/value pairs0279

that a server sends to a client, that a client will save somewhere on the client computer, storing that data.0285

And then, it will send that information back to the server on each request.0293

This is typically accomplished via cookies; and that is known as a client-side session.0298

A server-side session (which is what we are going to be discussing, and what is the functionality that PHP provides)0306

provides the same sort of functionality, except that the session data is going to be stored by the web server.0311

So, instead of storing your shopping cart data in a bunch of cookies on the client side 0318

that get passed back and forth between the client and the server, your session data is going to be stored on the server, 0322

typically in a file, or maybe even a database--or maybe even in RAM.0328

If there is a limited number of users connecting, you might have the capacity on your web server0334

to just store all of a client's information in RAM.0339

Instead of having a cookies that might be called 1001=1, you might have a text file somewhere called...that stores that same text data.0343

This is the file name, and this would be the file contents, which would be the same thing.0370

This information could also be stored in a database, and RAM as well.0376

Now, we are moving the state of the session from the client into the server.0380

Typically, the way server-side sessions are implemented is by making use of a unique session ID, known as an SID.0388

And what that is: every time a user starts a session--it connects to a web browser and says, "I want to start a session" 0396

(for example, it logs into a website), the web server is going to generate this unique ID.0402

It is typically a long, random number and letters that is considered unique enough 0407

to uniquely identify that user and this particular time that it is connecting to the web server.0416

The web server will generate this SID, and it uses that SID, that unique ID, to do two things,0424

which is part of what we just explained as part of sessions.0436

It is used to identify multiple HTTP transactions as being part of the same session.0441

For example, when you add multiple items to a cart, what is going to happen is: 0447

the session ID (SID) is going to be sent to the server with each request, every time you add an item to a cart.0451

And the server is going to be able to know then, by looking at the SID provided,0461

that those requests are supposed to be linked together; they are part of the same session.0465

It is also going to be used to access any stored data for the session.0470

For example, if you have this unique SID, and you send a request to the server, and you are trying to load up some data0474

that you had stored (maybe the state of your shopping cart), the server knows how to take this SID0484

and then use it to access any session data that has been stored on the server.0489

What happens (as was mentioned) is: the client passes this SID to the server on each request.0496

So, what happens is: when a session is started, the server sets a cookie with some unique ID, and it sends it to the client.0503

For example, let's say the client logs in; the server says, "OK, this is a valid login; now I'm going to start a session."0520

And it is going to send this cookie to the client.0525

Well, now every time the client goes back and requests a file from that particular website,0527

it is going to include the Cookie header in its HTTP request, which is going to pass along this SID.0532

So now, every time the web server receives a request from the client, it is going to have this cookie.0540

And the server is going to be able to say, "OK, this is part of this 1ABE session that is currently going on."0544

And it will be able to link to multiple transactions, and then also, it will be able to access any data associated with this (for example) 1ABE session.0552

We know that we can do this via cookies; and what happens is: there is only one cookie that is passed back and forth between the client and the server.0563

In our web store application, we had the server setting multiple cookies on the client--one for each item in our shopping cart--and that was to maintain state.0575

Well, now all we need to do is pass this unique ID back and forth via cookies.0583

And by presenting that unique ID to the server on each HTTP request, that is going to allow the server 0587

to get all of that state information that is already stored on the server.0594

Another option would be to use a URL parameter.0597

For example, we know that we can pass GET variables by appending them as query strings to a URL.0600

For example, let's say that we wanted to get a script called addItem, which adds an item to a cart.0609

We might be able to append the SID...for example, let's say we want to add item 1001, and this is the format that we use in this addItem script.0619

Well, what we can do is append this SID to each time we request a URL via GET from the server.0637

And what that is going to do is: then, when this information comes in, PHP is going to be able to extract this SID0649

and then know how to access session data, and also to link the transactions together.0655

This is not a secure method, and it is generally not recommended to be used.0660

So, all of the sessions that we are going to be doing within this course are going to make use of cookies.0668

And as we mentioned in our last lesson on cookies, that means that for users to use your website0673

(that has sessions that use cookies), they need to have cookies enabled on their browser, so that is one thing to consider.0680

And mainly the reason that this is considered insecure is because any time you have a URL, you could bookmark it.0686

For example, you could email your URL to a friend.0691

Well, if your URL contains your session ID, then that means that that person can just click on that link,0696

and if your session is still valid (let's say the session still hasn't timed out yet--and we are going to talk0701

a little bit more about the lifetime of a session), if that user clicks on that and provides that SID,0705

the web server is going to assume that it is you.0710

And then, that person is going to have access to your account.0714

That is why it is not used--one of the security reasons.0718

It is a lot more difficult to do that with cookies--if your friend wanted to be able to impersonate you in the same way,0721

and it wasn't using a URL parameter, they would have to have access to that cookie0728

that PHP set on your computer, and then be able to send that over, which is more difficult to do.0732

As mentioned, server-side session functionality is built into PHP.0742

And PHP typically uses a cookie; as mentioned, it can use URL parameters, but the preferred method,0746

and the method we are going to be using, is to use a cookie.0752

And that cookie is going to contain the SID of a particular session.0754

And this cookie that contains the SID is sometimes referred to as a session cookie.0759

And what that enables us to do, as we had mentioned, is: it is going to allow that SID to be passed 0766

from the client to the server on each request, so that a client can identify itself as part of a particular session.0771

Now, when that server receives that cookie from a client, it is going to be able to look up some session data for that server.0778

Well, in PHP, we had mentioned earlier that using server-side sessions, a server could choose to store session data in files.0786

Maybe it has a separate file for each session; it can store it in a database; it can store it in RAM.0796

Well, in PHP, session data is stored in flat files, or just text files.0801

And what it does is: for each unique session that is initiated, it is going to create a file in which to store any session data.0808

It stored these files in the location specified by session.save_path directive.0820

So, whatever that directive is set to in your php.ini file--that is where these temporary session data files will be stored.0828

In XAMPP (which is what we are using in this course), by default, this save_path directory is set to the tmp directory of your xampp root directory.0837

We can go and look at our php.ini file, and we can see that there is a section within php.ini that discusses configuration options related to sessions.0848

And we can see that session.save_path is set to C:Users/Educator1/xampp/tmp, which is saying that0861

any time data files are created for a new session, they are going to be stored 0869

in the tmp directory of our xampp directory, which we have stored in our user directory.0873

Any time you want to have a script that uses session functionality, you need to call a built-in function called session_start.0883

And what that will do is: whenever that is called on a script, it will test to see if a session currently exists.0892

And the way that it does that is: it checks to see if the user, when they are requesting a particular page,0898

has passed an SID to that script by either a cookie or a URL parameter.0902

If not, it creates a new session, which is going to involve generating a new SID.0907

And then, when it returns the response from that particular script back to the user, it is going to set that cookie to the user.0911

Or if it does find an SID in the client's request, then what it is going to be able to do is continue the existing session.0917

And it is going to be able to do things like access any previously stored session data.0925

As mentioned, session_start is going to generate an SID, and will send a cookie to the client with that new ID, if the session is new.0930

And the value of the cookie that it sets is the session.name configuration directive in php.ini.0940

If we look at php.ini, the default in PHP and in XAMPP is to name a session PHPSESSID.0954

Any time you start a new session with PHP, with a default setup, when a script calls session_start for the first time in a session,0964

a cookie is going to be sent back to the client that is going to be called PHPSESSID.0976

And it is going to be set equal to whatever random session ID was generated--for example, just some random string that it comes up with.0985

If a session is being continued, what session_start is going to do is look for a URL parameter or a cookie that is named session.name.0997

So, it might be a GET variable called PHPSESSID=.... if this was a URL parameter.1006

Or it would look for a Cookie header in an HTTP request that will have a cookie named PHPSESSID1023

equal to whatever the random session ID was, assigned to this previously-started session.1033

What it can do is use that session ID, then, to access any previously-stored data, which we are going to talk about in a minute.1040

One thing to note is: if you are using cookie-based sessions (which, again, is the typical scenario used),1047

you must call session_start before any output is generated for your script.1053

And the reason for that is that, because this session_start method will send a cookie to the client when a new session is created,1058

it is going to be setting a header, the Set-Cookie header, and it is going to be calling the setCookie method.1068

And as we have learned before, any time you want to add HTTP headers to a response you are sending back to a client,1074

you need to do so before any output is generated.1081

Let's take a look at an example that we have.1085

It is two scripts: one is called sessionStart.php, and what it does is just calls this session_start method,1088

which says, "When the user views this script, it is going to start a new session."1096

So, when the user requests this page, if an SID hasn't been provided by a cookie, for example, it is going to go ahead and generate an SID.1100

And then, it is going to set that PHPSESSID cookie, and it is going to send it back to the user with the response.1109

And in this case, the content of this script that it returns to the client is just some information about the request sent by the client,1116

and then also information about the response header sent by the server.1125

It uses a couple of methods here: getHttpResponse and getHttpRequest, which are just functions that I have created.1130

When you look at the lecture_examples directory, you will see that there is a file called utilLIB.php.1138

And what it does is: it goes ahead and builds up this string that represents an HTTP header response.1142

We can quickly see what is going on when a session is started, as far as cookies go.1149

So, if we go and load this page, example1, and we click on start_session, for example,1155

if we look down here at Firebug before we load the script, we can see that currently there are no cookies1163

being sent by the client when it is making a request to the web server.1169

That means that no cookies are set for this particular path and this particular domain.1175

And you can see that by looking at the HTTP request.1182

Now, when we request sessionStart.php, we can see a couple of things.1184

First of all, we can see that when the client requested the page, it requested sessionStart.php, 1190

and it didn't provide a cookie, because no cookie existed for this domain and path.1195

However, when we received our response back, we can see that the server did set a cookie.1200

It set a cookie called PHPSESSID, as we expected.1206

And then, as we can see, it set it to this random string of letters and numbers.1209

And it also specified a path for this particular cookie.1213

And so, if we look down in more detail at the request and response headers, we can see that,1217

when the user requested the page, there is no Cookie header, because no cookie was previously set.1227

However, when the response came back, there is a Set-Cookie header that was provided by the server.1233

So now, if we go to look at a second page, continueSession.php, what this is going to do is be another page that is going to continue our session.1240

And so, all it does is: at the beginning, it calls session_start.1250

What is going to happen is: now that our client has had a PHPSESSID cookie set, when it requests this new page,1253

it is going to send that cookie along, because this is in the same directory, so its domain and path of that cookie are going to match.1259

And then, what is going to happen is: PHP is going to know that it is part of the same session.1265

So, what we are going to see is that, when we look at the response from this method,1269

the server is not going to send back a setCookie parameter, because when it calls session_start,1274

it can already see that there is a cookie that has been created.1280

If we go to continueSession, we can see that, in our request, we have now passed along this PHPSESSID cookie 1283

that was generated by the server and was set on the client.1291

So now, we have identified to the server, when we requested continueSession.php, that it says,1296

"Hey, we are part of a PHP session, and this is the ID that we have been assigned for this particular session."1302

Now, when the response from the server comes back (which is just the output of this page),1308

we can see that the setCookie parameter is empty; there is no Set-Cookie header.1312

And that is because it doesn't need to set a session cookie, because it already detects one.1318

And so, that is how a session would be continued.1323

One thing that session_start also does is has the effect of making session data available in a script via this superglobal variable $_SESSION.1329

When you call session_start, if a session has already been created, it recognizes an SID via a cookie.1341

Then, what it is going to do is populate this superglobal array session with any session data that has been previously set.1347

For example, you may have added an item to a shopping cart.1354

And what you do is add that item to this...in a previous script, where you accessed session, you may have saved an item to a shopping cart.1357

And you do so by directly accessing this $_SESSION associative array.1365

It is an associative array, and you add data to your session simply by adding key/value pairs to this $_SESSION superglobal.1372

For example, let's say we wanted to add a session variable called username, or we want to add session data that represents a user's name.1380

We can set a key called username in the _SESSION superglobal, and then set it to a string.1388

In this case, it is jsmith, which maybe is a username for a particular user.1394

In this case, username is what is known as a session variable.1399

When you add session data to this _SESSION superglobal, the key that you use is called the name of the session variable.1404

In this case, we are saying we are creating a session variable called username; we are setting it equal to the value jsmith.1416

And one thing to note is that the keys have to be strings, just like in any other associative array;1424

but the values can be any data type--they can be objects or even arrays.1429

So, you can store whatever you want in there--you can store any kind of data.1434

And you can store as much data as you need to within the _SESSION superglobal, simply by adding new keys...1436

for example...I don't want to do password, but...maybe you would add a name session variable that represents the name of the user.1445

So now, every time you go to a page, session_start is called at the beginning of that page.1459

An SID is going to be recognized by PHP.1464

It is going to go out and load that session data associated with that session ID, and populate it into this session variable.1467

The way that it does that is: it loads the data stored in the session's data file, which is stored in session.save_path.1476

We talked about...each time a new session is created in PHP, there is a temporary directory in which PHP will create1485

a data file in which to store any session data.1491

Any time you set session data, for example, via this method here, what happens is:1494

when that script ends, PHP goes and updates this data file that is associated with this particular session.1499

And then, the next time, when you come back to request another web page, when you pass it the SID,1506

it can use that SID to go up and look up that particular data file, and then load the data out of it into this _SESSION array.1512

And we are going to take a look at how that works.1519

For example, if we go and look at example-2, one thing that we can see is that the default path1523

in the PHP setup for a session cookie is / , which means anything on the domain that the cookie was set at, which in our case is localhost.1533

We can see that our cookie is still being passed along, even though we are on a different example, 1544

because we are still under the root path of this particular domain.1550

In order to do this example, we are going to need to delete the cookie.1555

And one of the ways you can do that is just a shortcut to clear your recent history in Firefox.1558

And we can say, "Delete all the cookies from the last hour."1564

So, if we clear that, and now if we refresh the page, we can see that there is no Cookie header,1568

so we are no longer passing a session cookie to this page.1575

What we have is a script called setSessionVar, which is a script that starts a session.1579

So, it is going to generate this new SID, which it is going to send back to the client with this response.1587

And then, it is also going to add a session variable called username and set it equal to jsmith.1591

And then, it is just going to output a little message and a link to a page that is going to allow us to view a particular session variable.1597

When we go ahead and load this setSessionVar page, what we can see is 1605

that we have had a Set-Cookie header sent back to us with a new PHPSESSID cookie value.1612

And so, here is another random string; and that is what we are going to use to identify ourselves in this new session.1621

Now, if we go and look at our xampp directory, and we look at the tmp directory (which we had talked about),1627

we can see that there are a bunch of files here with random names.1638

They start with sess_ , and then the name of the session ID that is generated for a particular session.1643

So, any data we store for a particular session gets stored in a data file that has a name that includes the session ID as part of the name.1649

So, if we look at our session ID generated, it was hgjc8t, for example--that is what it begins with.1657

If we look at our directory, we can see: here is a session file hgjc8t, and so on.1666

So, that is a data file that was created when we called session_start.1673

That is another thing that happens when you call session_start: it goes ahead and creates a session data file.1678

And it is able to look it up via the session ID.1684

The way that we access session data is: what you need to do is: on any script 1690

where you want to access data that has previously been stored in a session, you need to call the session_start method.1694

And the reason for that: what that is going to do is load any data that you have previously stored in your session 1700

from that session's data file, which is identified by the SID.1705

And it is going to load it into this _SESSION superglobal.1709

So, any variables we have previously set..for example, we have previously set the username variable in this; 1713

well, now we are going to have access to it.1718

And the way you do it is simply the way you would access any other associative array or superglobal.1720

You have the name of the array, and then, using the square bracket syntax, you specify the variable's name.1725

Our session variable username, which we associated with the value jsmith...1732

when we call this echo statement on a script where we have also already called session_start,1739

and we have previously set the username to jsmith, this statement is going to echo 1744

the string jsmith, which is going to load from the _SESSION array.1749

If we go and look at...1753

Well, our setSession script has a link that says Next Page, which links to a page called getSessionVar,1756

which we are going to use to demonstrate how to access session data.1763

If we go look at getSessionVar, we can see that, beginning at call session_start, because you have this cookie now1767

that you have passed along, because you have started a session when you request this page,1773

you are going to be passing along that session cookie that was generated--that hgjc8t...whatever ID it was.1778

Well, when this method is called, it is going to read that cookie.1784

It is going to be able to go to our temporary directory, load any data that is stored in that file, and then populate the session with it.1787

And one of the things we can do is look at this file.1796

And we can see that it has some information.1811

Since we have already set a variable to it, we can see that it has an encoding that PHP uses1813

in order to serialize--take this data that we are storing as a session and serialize it so that it can be stored in a file.1820

So, we can see here that in this terse way, we can tell that we have a username variable called jsmith.1829

In this particular case, to decode this, it is saying that there is a username variable; it is a string of length 6; and the value is jsmith.1836

Any time you add data to a session, it is going to get added to this file.1845

So, there is encoded text within that file.1849

What is going to happen is: session_start is going to load that data that we just saw in that session file into the _SESSION array.1856

And now, we can access it; and we can go ahead and output session with the key name username.1863

And it is going to output that username that we had previously set, which is jsmith.1870

If we go and click on Next Page, we can see that we have been accessing the session variable username.1875

And we can see that it was able to access jsmith, which we had set on the previous script.1882

Also, notice that, when we called session_start, there was no set Cookie header, 1885

because when we requested this page, we already passed along this hgjc8t session ID cookie.1891

It knows that a session has already been started.1899

We have learned how to add session data; we have learned how to access session data;1904

now, we are going to talk about how to delete it.1908

The way you delete data is the same way that you would delete data from any other associative array.1910

You can just call the unset method on the _SESSION superglobal and specify the name of the variable for the data you want to delete.1915

For example, to delete this session variable username, we simply call unset on the _SESSION superglobal, with the key set to username.1925

We have another script that getSessionVar is going to forward to when we go to Next Page.1937

It is going to go to a script called deleteSessionVar; and if we look at our deleteSessionVar script,1943

we can see that it starts the session--and again, this method has to be called in order to get access to the session.1948

It is kind of counterintuitive, but to delete a session variable, we have to start the session to gain access to it.1956

So, this is going to give us access to the _SESSION superglobal.1962

And here, we are deleting the session variable username by calling unset on _SESSION with the key username.1966

Now, when we go to try and output this session variable username, because it has been unset--1972

no longer exists--we are going to get an error down here.1978

And if we go and click on Next Page, we can see that there has been an undefined index.1980

You have tried to access username in _SESSION, and it doesn't exist.1986

What we can do is a ternary operator to just clean up this code a little bit.1991

We are going to test if the session variable is set, which means, "Does that session variable exist?"2005

If it is, we are going to set this variable username equal to the value it is set to.2011

And if not, we are going to set it equal to, let's say, 'does not exist'.2017

So now, when we reload our script (I need to update this part here to output this new username variable),2024

instead of getting this ugly message, it is going to say (oops, it looks like I left out a square bracket)...2034

we can see that we get an output that says, "This value does not exist."2053

Now, one thing to note is that that only deletes this particular session variable, username.2058

Let's say, for example, on our getSessionVar, we add another session variable.2063

Let's say we create a session variable called name and set it equal to Joe Smith.2070

Now, if we go back to getSessionVar and we re-click on the link and we reload the page, it is going to create this new session variable.2080

When we go to click on deleteSessionVar again, it is going to unset username, 2089

but that other one will still be available, because we have only unset that one.2095

So, when we go down here, we can also echo this second variable.2097

And I am not going to use a ternary operator to test for it, because we know it is going to exist.2114

What we do is: if we go back to this page, it is going to reload the page...2118

Again, because we have unset that previous username session variable, it is not going to be able to output that.2123

But what we can do is: when we go back to our deleteSessionVar page, what it is going to do is:2130

it is going to have this new name variable created.2135

And so, it is going to output the username, where, in this case, the string says 'does not exist.'2140

But it is also going to have access to Joe Smith.2145

That is just a comment that lets you know that unset only unsets that particular variable.2147

And it sort of makes sense; it is pretty intuitive, but I just wanted to make sure that you were aware of that--that each variable is considered separate.2151

So now, if we go ahead and specifically unset the name variable, as well, when we reload this script,2159

it is going to try to output it, and again, we are going to get an error.2166

Now, we are going to get an error saying it can't find the variable name.2170

There are a couple of things we can do to configure sessions in PHP.2176

Some of the more common configuration options that you use are to configure how session cookies work.2180

We know that cookies have an expiration; they have an expires attribute; they also have a domain and a path attribute,2185

which allows you to set the particular name that a cookie is good for 2191

and the path that it is good for, as well as how long that cookie is good for.2195

By doing so, for example, if we set the expires...the way you set the expiration date on a session cookie is:2200

you use this session.cookie_lifetime configuration directive, and you can set it to the seconds from when that cookie is created.2210

So, maybe we want our cookie to be deleted in a half hour.2219

That means that, if our client tries to come back to that website and continue that session a half hour later,2222

it is not going to pass that cookie along anymore, because it is going to be expired.2227

Our web server is not going to recognize that, and it is going to maybe output a message that says you don't currently have a session.2230

And then, the other thing we can do is set the domain path for a cookie, if we want to set specific cookies for certain parts of our website.2237

If we go and look at php.ini, in the session section, we can see that there is a cookie_lifetime configuration parameter,2243

which, if it is set to 0, means the cookie expires whenever the browser is closed.2258

It has a cookie_path, which defaults to the root directory of whatever domain it is on.2263

And then, because domain is set to blank, it sets it to whatever domain that cookie is generated for.2267

If we go and view our cookie for this particular session that we had created in our last example,2273

and we look at localhost, we can see that we have a cookie called localhost that has been created.2280

It has a path of just a forward slash, which is the root path.2286

And we can see that the name of the cookie is PHPSESSID, and its content is the unique SID that was generated.2290

What we can do is: we have a script in the example-3 directory...let me just clear cookies...sessionConfig.2303

And this just provides a little bit of output about these configuration directives.2316

It provides information about the two configuration directives we talked about before:2324

save_path, which says that the session files are stored to this directory xampp...2326

It has the session_name directive, which we saw was PHPSESSID; and then, we can see that it has these cookie configuration directives that we just saw the values for: 0, empty, and path.2334

And if we look at this page, it actually calls session_start at the beginning.2348

So, when we view this page, it has started a new session.2351

And if we look down here at our response, we can see that there is a Set-Cookie header that has a new PHP session ID set.2354

Well, if we go and look at this cookie, we can see, again, that it has this unique ID.2365

But its path is set to the regular path, and its host is set to localhost.2376

Well, let's say we want to change that, so that when this script starts a session,2380

it generates a cookie that only works for this particular path.2385

For example, this example-3 directory--we can go to our php.ini file; let's explicitly set the domain to localhost;2389

we'll set the path equal to the path of the directory of this particular example.2400

And let's say we want the cookie to expire in 60 minutes, which would be 60 seconds times 60 minutes--3600; it is going to expire in an hour.2406

We have changed the configuration; so we go ahead, and we are going to restart Apache.2414

If we go ahead and delete the current cookie that we have, and we reload this page, we are going to see a couple things.2422

We are going to see that now our session cookie has a lifetime of one hour.2429

It has a domain explicitly set to localhost, and it has a path set for this example-3 directory.2433

So, this session is only going to work for scripts within this directory.2438

If we look at the Set-Cookie header, we can see that it provides an expires attribute; it provides a path attribute and a domain attribute, as well.2442

Those are things to configure the session cookies.2458

There are also some configuration directives that determine whether PHP should use cookies to manage its sessions,2461

or use a URL parameter, as we had talked about, to pass a session ID between the server...2467

There is a directive called session.use_cookies that says that the server should use cookies2473

to send the session ID to the client, and to expect it back from the client in the form of a cookie.2480

There is another option called session.use_trans_sid, which is saying to use a transparent SID.2486

What that is going to do is: when that is enabled, and cookies is disabled, any time you generate output2493

for your particular script, what PHP is going to do is go through and find any source or href...2499

basically, any links that you have on your page--and it is going to 2505

append a query string to them that contains PHPSESSID equal to whatever the session ID is.2508

What that is going to do is: any time a user clicks on those particular links,2515

PHP is going to be able to get that session ID via this GET variable.2518

One other thing that you can do is: there is a configuration directive session.use_only_cookies,2523

which explicitly sets and forces that you can only use cookies for transferring SID's.2526

And that is the safe and secure way to do it.2532

And because of that use_trans_sid configuration directive, managing SID's is strongly discouraged for security reasons.2536

And if we just look at our sessionConfig, we have a section that I have commented out.2548

And it is just going to output some of these configuration directives that we have.2558

We can see that we are using cookies--we are not requiring the use of cookies, but we are also not using this transparent SID.2566

For the homework challenge, what I want you to do is create a couple of pages that are going to make use of sessions.2577

I want you to create an HTML page called login.html that is going to contain two text inputs: one called username and one called password.2584

And then, when you submit that form, I want it to be submitted to a script called welcome.php; and have it use the GET method.2592

What welcome.php is going to do is start a session.2601

And then, it is going to attempt to verify a user's login information.2605

We are going, for this homework example, to consider a user login...if they provide any non-null value for username2610

(so if they provide any text for their username), and if they provide the password (which is the string '1234'),2616

then we are going to say, "OK, this user is verified and can be logged in."2622

If the user is verified, then I want you to create a session variable called username.2626

And remember, to do that, we are going to be using the _SESSION superglobal.2631

And then, set its value equal to the username value that was submitted on the form.2635

If it is not verified, then I want you to just ensure that no username session variable exists.2641

And the way that you are going to do that is with the unset method.2647

On the same page, if the user was valid, I want you to output a message that says the user has been successfully logged in.2652

And include a link to another page that you are going to create, called member.php, which is a special members-only page.2659

And it is going to require that a user be logged in, in order to view that content.2665

If the user is not valid, just output an error message stating that the username and password were incorrect.2669

The way you can test to see if a user is logged in is: you can test to see if the username session variable is set, using the isset method.2675

And so, if the user was able to log in...we saw that, in a previous step of this homework,2685

you are going to go ahead and set a session variable called username;2692

so, if we test if that username variable exists, then that is going to let our script know that the user has been logged in.2694

And so, that is how you are going to tell whether to output an error message or output a message about the members-only page.2700

On the members-only page (member.php is a script you can only view via logged-in users),2706

if a logged-in user tries to view this script, then go ahead and output the user's username they provided on login.html.2712

And so, that is going to give you practice with accessing session data.2719

You are going to have to access that _SESSION superglobal array in order to get that username that was provided.2722

And if a non-logged-in user tries to view the page, just output an error message stating that the user must be logged in to see the page's content.2728

Again, the way you can test if a user is logged in is just to test if this username session variable has been set,2735

because we know that once a user has been validated or verified, that username session variable gets set.2741

Your script should make use of the session_start method, the _SESSION superglobal,2748

and then also this unset method for deleting variables...and actually the isset method, as well,2753

for a construct for testing for the existence of a session variable.2759

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2763

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application.0005

And we are going to be incorporating what we learned in our last lesson regarding sessions.0008

In this lesson, we are going to go over one new version of our web application; it is going to be called version 12.0.0014

And what we are doing is converting the web application from using client-side sessions to manage our shopping cart.0019

And the way that worked is: we were sending cookies to the client that contained all of the information about a shopping cart.0028

For example, for each item we added to a cart, we would create a cookie with that item number,0035

and then set the cookie's value to the quantity of that item in the cart, 0039

and send that cookie to the user that would be stored on the client side.0043

And then, every time the user would go back to our website to view the cart or to add another item to the cart,0046

it would send all of these cookies back; and that is how we maintained the state of our shopping cart.0053

We maintained it on the client side, in what was essentially a client-side session.0057

Now, we are going to be converting over to using PHP's built-in server-side session functionality.0062

Again, we are just converting using client-side cookies to storing all of our shopping cart state on the server side.0070

What we have done before: if we look at our previous version of viewCart.php,0078

in the beginning of the script, what we would do is load our shopping cart object, 0084

or build our shopping cart object up, using this buildCartFromCookies method.0091

And we would pass it the _COOKIE superglobal, which would contain any cookies that we had previously set for items we would add to our cart.0095

This function, as we learned before, would go through, look at all the information in these cookies, and build our up our shopping cart object.0102

Then, what we could do is: if we needed to add an item to the cart, what we would do would be 0109

to make an update to the cookie for that particular item.0114

We would increase its quantity by 1; or if it was a new item, then we would just set a brand-new cookie for it with the value equal to 1.0117

In addition, if we wanted to remove an item from a shopping cart, 0126

we would have to set the cookie for that particular item, using the item ID, and set it to expire in the past.0129

And that would essentially delete that cookie, so that the next time the user views your page, it doesn't get sent back to our web server.0138

And therefore, the server doesn't know that that item is in the cart anymore.0144

That is how we removed an item from a cart.0148

Well, now what we have done in our new viewCart.php is: we are making use of sessions to store this information, and it really simplifies things a lot.0154

In our viewCart.php, the first thing that we do in any page where we use sessions is:0164

we call our session_start method, which is going to generate a new session and a new session ID, 0167

if one has not already been created--if no session ID cookie was passed to the server.0174

If not--if it is a continued session--what it is going to do is look at the cookie passed by the user,0181

look up the data associated with that session ID, and load it into the session variable.0189

What we can see here is that the way we load our cart method now--rather than using the buildCartFromCookies,0195

we simply test if the session variable cart exists, using the isset construct,0201

which means that we have previously had a Cart object in our session.0207

And I should also mention: the way we implement our shopping cart using PHP sessions is:0212

we store a shopping cart object in the session array; it is a Cart object, and it has the name cart.0219

This is testing to see, "Does this cart session variable exist?" (which is a Cart object).0228

"If so, load it from session into this cart variable; if not, just create a new, empty Cart object."0233

And then, what we do is: whereas before we were looking at cookies...if we wanted to add an item,0242

we would have to set a new cookie that would set it with a quantity incremented by 1.0249

If we wanted to remove an item, we would have to call the setCookie method and set the cookie for a particular item to the past.0254

Now, what we are doing is simply using the cart's built-in methods to add items to and remove items from the cart.0260

Here, we have the addItem object method and the removeItem object method.0267

And we use those to update our cart, and then what we can do is: to save the cart between sessions,0271

rather than sending cookies back to the user with all of this information,0277

we just save this Cart object that we have updated to our session, using the _SESSION superglobal.0281

So now, this updated cart will be added to the session.0290

The next time that we view a page on our website that calls session_start, we are going to have access to that cart.0293

And in particular, it is going to be checkout.php.0299

What we have done, as is mentioned, is: in viewCart.php, we used the object methods of our Cart object0306

to update a shopping cart, as opposed to updating the cart with setCookie calls.0312

And then, we save our shopping cart object to a session variable named cart.0317

Now, what that is going to do is: we also have updated checkout.php so that, when it calls session_start0323

at the beginning of that page, it is going to have access to this shopping cart that was saved in viewCart.0330

So, let's say we have added a couple of items to our shopping cart.0335

When we go to checkout.php, it is going to be able to load that shopping cart object from the session, and then successfully process the order.0338

If we take a look at, for example, our old checkout.php, what it did was the same thing that our viewCart.php did.0346

It would look at all the cookies sent over from a client that contains information about a shopping cart,0354

and build up that shopping cart, and then it would go ahead and process the order.0359

And one of the things that it would do was: after the order was completed, it would go through 0363

and specifically delete each cookie for each item that was in the shopping cart by manually calling this setCookie method--0367

which was somewhat tedious; and so, we are going to see that that is much simplified in our newer version.0375

Now, when we complete an order, and we want to empty the shopping cart,0381

instead of having to unset all of these cookies, what we are going to do is just unset a session variable.0385

If we look at our new checkout.php, we can see that we call session_start at the beginning,0390

which is going to give us access to this _SESSION superglobal.0394

We are going to test to see if the cart session variable exists (which would be a Cart object).0398

If it does, we load it from the _SESSION superglobal into cart; if not, we create a new Cart object.0406

Then, we simply perform a test that says, "As long as the cart is not empty, then we are going to process it."0411

"If not, we are going to output an error that says your cart is empty," because what that means is:0415

if there was no cart that was previously set up for the session, it means that there were no items in the shopping cart.0424

And so, that is how we test for that.0429

Once we have set that cart variable to the shopping cart object from our session, 0433

we go ahead and follow through with completing the order, as we had done before.0439

The one difference is that now, when we empty the shopping cart after an order is successfully completed,0444

as opposed to looping over the _COOKIE superglobal and deleting all the cookies for our items in the shopping cart,0450

we are simply going to unset the session variable cart.0455

What that is going to do is delete it from the session.0459

So now, when we go back and view our cart page, specifically what would happen is:0463

at the beginning of viewCart, it would try to load the cart from the session; it wouldn't exist, and so it would have an empty cart.0468

And then, when we have an empty cart, it would show a particular message.0478

Let's go ahead and take a look at how this works in action.0481

If we go to Electronics, for example, and let's add a television to our cart:0486

well, when we go to viewCart.php, what it is going to do is start a session.0494

We can see that it sets a session cookie, PHPSESSID, and that is what we are going to pass 0497

back and forth between the client and the server in order to maintain state.0501

And then, let's add another item, a Sporting Goods product--let's add a basketball to our shopping cart.0506

We go to Add to Cart; now, what we can see is that our shopping cart contains both items.0513

The way it is able to do that is that, when that new viewCart page is loaded, it starts a session, 0518

and it is able to go and look up this cart session variable, load the cart information,0527

and then viewCart knows how to output that cart to display the items in the cart.0533

So now, let's say we want to go ahead and check out.0540

We'll just enter some sample information.0544

And so, now what has happened is: this checkout.php knows about our cart, and that is how it is able to calculate the total,0556

because at the beginning of checkout.php, it loads the cart from the session.0565

So, that is how it is able to calculate the cart total here, which we are outputting for the user.0570

And when we submit the form, we can see that the order was successfully completed.0575

It has access to the cart total.0586

And one thing to notice is that we can see, when we submitted this form, that our PHPSESSID cookie still exists.0589

We have ended the session, but our session cookie still exists.0601

That said, we have unset our shopping cart object.0605

So, if we go back to viewCart.php, it is going to show that our shopping cart is empty.0612

That shows that we have eliminated the shopping cart data from our session.0618

But again, if we look at this page, we can see that we are still passing this PHP session cookie from the user.0623

So, essentially, we have not effectively ended this session.0630

We have deleted our session data, but as far as our web server is concerned, every time we are requesting a page,0633

it is still considered part of the same session, because we are passing this cookie back and forth.0639

And that is something that we are going to address in our next lesson, 0643

which is going to talk about how to properly end and destroy a session, 0646

so that when you are done and your shopping cart is empty, that session is completely over.0650

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.0656

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing our discussion of sessions, and we are going to learn about how to properly destroy a session.0005

We are going to briefly talk about what the destruction of a session implies--what it actually means.0014

We are going to go over a built-in function to PHP that is used to destroy session data, called session_destroy.0019

And then, we are going to talk about some additional steps that you need to do, in addition to calling this session_destroy method,0027

to effectively end or delete or destroy a session.0033

That is going to involve manually deleting all of the session data and manually deleting session cookies.0039

Then, we are just going to go over a review of all of the steps that are involved in successfully ending a session.0046

And then, we are going to briefly talk about the topic of garbage collection, which talks about what happens 0052

if a session is not successfully ended--what happens to that session data.0057

When either a client or a server determines that a session is over (for example, if a client wants to log out, 0065

or a server decides that the user hasn't had any activity in a certain amount of time),0070

it can end that session; and that is called destroying the session.0076

What destroying the session does is undoes the two things that a session does:0082

namely, it cuts the link between any previous and any future HTTP transactions (because that is part of what a session does--0088

it links multiple requests together, so that they are considered part of the session between two parties0097

over a specific period of time), and it also gets rid of any of that session data associated with that particular session,0102

because that data is transient data, and when the session ends, it is no longer needed.0111

So, destroying a session is effectively getting rid of that data.0115

In PHP, for example, what that means is getting rid of that session data file in the tmp directory on the server, 0119

freeing up that disk space to be used for other sessions.0126

PHP provides the session_destroy method that is used to destroy a session.0132

What it does is ensures that any session data stored on the server will be deleted.0139

All of those session files that we had looked at in previous lessons in the tmp directory (like sess_ and then the unique session ID)--0147

session_destroy, when it is called, deletes that session file, so that data is no longer accessible.0159

One thing to note about the session_destroy method is that, in order for you to call it in a script, 0166

it has to already have or know about an initialized session, which indirectly means that, in order to call session_destroy,0174

you have to call session_start on that script before you do it.0181

This is a little counterintuitive, because you think, "OK, I'm destroying the session; why do I need to start it?"0185

But that is part of the process; so, in any script where you call session_destroy, before you call that method, you also need to call session_start.0189

Let's take a look at what session_destroy actually does.0199

We have a script called setSessionVar; this is similar to what we used in our last lecture.0207

What it does is starts a session and sets a username session variable equal to jsmith.0215

And then, it outputs a link to getSessionVar.php, which is a page that allows us to access that session variable.0221

Because it accesses session variables, it needs access to the _SESSION superglobal; in order to get that, it has to call session_start.0230

So, it is going to call session_start, which is going to see the cookie that the client provided with the session ID.0237

And then, it is going to use that to load the _SESSION superglobal.0243

Here, we have done a little bit of error checking to make sure that this username session variable does exist when the user comes to this page.0247

It is just checking: if that username session variable is set, go ahead and set this username variable to the value of that session variable.0259

And if not, we are going to set it to a string that is an italicized string, nonexistent, which means that it doesn't exist.0268

Then, what we do in the body of our HTML is: we are simply outputting that particular username that is part of the session, assuming that it exists.0279

We also output a new link that says to destroy the session; it is going to go to destroySession.php.0290

What that does is call our session_destroy method; now, as mentioned, in order to call session_destroy, you have to call session_start previously.0298

So, it calls session_start and then calls session_destroy.0308

And then, the body will attempt to output this session variable username, if it is still valid.0311

And it has the same ternary operation up here that tests for the existence of that username variable,0319

and will set username equal to that value, if it has been set.0327

And the reason why I have included this here (you might wonder why I am including that in a statement that is destroying the session)0333

is to show you the incomplete nature of what session_destroy does.0340

For example, this is our temporary directory; I'm going to delete all of our current session data files that we have in there.0346

If we go ahead and make sure that any session cookies are deleted, and then if we go to example-1, and we go to setSessionVar,0353

we can see that we have been set a session cookie that starts with r4gla.0361

If we go and look at our temporary directory that stores our session data files, we can see a data file that corresponds to r4gla.0368

The script is going to set that username variable; again, if we look it, a session variable is going to set it to jsmith.0379

So, when we click on nextPage, which is going to go to getSessionVar, we can see 0384

that we are able to output and access this jsmith session variable that was set.0389

Again, we can see here that we have our r4gla cookie that was sent from the client to the server,0396

so that it knows that it is continuing this r4gla session, and therefore has access to that session variable that was set as part of that session.0402

Now, if we look here, we can still see that this session file exists.0411

And when we click on destroySession, we are going to notice a couple of things.0417

First of all, we can see that the session data file no longer exists, because session_destroy does that.0422

However, we can see that we are still able to output the username session variable.0430

If we go back and look at destroySession, we can see that, even though we have called session_destroy, we still have access to this session variable.0436

And the reason for that is that, when session_destroy is called, it doesn't destroy that session data file until after the script is finished running.0446

So, because of that, the information stored in that session data file, which has been loaded into _SESSION, is still available for the rest of this script.0454

That is why we are able to access that down here, and that is one of the issues that we are going to talk about, about destroying a session.0462

You want to manually destroy any session data that you already have, so that this can't happen--0467

because, in a way, it doesn't make sense that you are destroying a session, yet down here you are able to access that session information.0471

One thing to note is: if we go ahead and refresh that page, what is going to happen is:0479

if we look back here, when we start the session, it is still going to have that session cookie.0484

It is going to try to load data for that particular session, but because that data file has been destroyed,0490

it is not going to be able to load it, and so this username session variable is not going to exist.0495

And so, we are not going to be able to output anything.0500

If we go ahead and refresh the page, we can see that it shows nonexistent.0504

It shows that it actually did delete that data file, but when that script is immediately run, those session variables are still available.0507

To counteract that imperfection of session_destroy...not necessarily an imperfection, but intuitively, you think that0519

if you call a function session_destroy, it is going to completely end a session, but that is not necessarily the case...0529

As mentioned, one thing it doesn't do is delete the session data immediately.0537

So, it is still accessible in the rest of the script.0540

What we need to do is explicitly delete any session data, so that future portions of that script will no longer have access to that data.0544

And we can do that (as we learned about deleting session variables) using the unset method.0553

If we go and take a look at example-2, it has the same exact setSessionVar script and getSessionVar script;0560

however, its destroySessionVar script is different, in that now it actually unsets this session variable.0570

So, whereas in our last example, we tested for the existence of the variable and then set the variable username0577

to that session variable if it did exist, here we are explicitly unsetting, or deleting, the session variable.0586

Then, we call session_destroy; now, because we have called this unset method, when we go down here0594

to actually try and output the session variable username again, we are going to see that we are not going to be able to do that,0599

because we have unset that variable; so we have eliminated one of the problems with session_destroy.0606

We have now made that session variable inaccessible to the rest of the script.0610

So, we have a test down here that tests to see if that username session variable exists.0614

If it doesn't, it is going to say it is destroyed; and if it does, it is going to output it.0619

And assuming that everything works, we should never reach this else statement, because we are unsetting this session variable up here.0624

If we go and look at this new example, and clear our session cookies, and go to setSessionVar,0634

it is going to start our new session: am1j67 is the beginning of that session ID.0649

If we look at our temporary directory, we have that am1j67.0654

Now, we go to Next Page; we are going to have access to that session variable username, so we are able to output it.0659

Now, when we go to destroySession, it is going to output a message "session destroyed."0664

And additionally, in our temporary directory, we no longer have that...I don't remember what the exact name of that session ID was,0668

but we no longer have that session data file anymore, because session_destroy destroyed that after the script ended.0677

But as you can see now, the "session destroyed" message gets output, because we can see down here that0684

that session variable username is no longer available.0694

Another way (if we go back and look at our slide) to delete session variables: instead of going through0700

and individually unsetting each variable, you can just set the _SESSION superglobal array equal to the empty array,0708

which is going to erase any key/value pairs that it had.0715

So, it is going to delete any session variables that you have already created in that session.0719

And in general, that is the preferred method--the main reason being that it is easier to do, 0728

and you don't have to remember every single session variable that you may have set.0733

We can go and update our script: instead of calling unset on username, we can just set _SESSION equal to the empty array.0737

And then, just to confirm that this works, we go back and delete our session cookie, and we run everything again.0751

Create a new session; v1hnaq is our session file; we are able to output that session variable.0761

Now, our session is showing that it was successfully destroyed, so that effectively deleted that variable.0774

And we no longer have that session file, which was v1hnaq; if you look back, it has been deleted.0779

So, we have still been able to delete all of our session data, and we have been able to destroy the session file.0785

Now that we have done that, there is still one more part of the process that we need to do.0794

It is: we have been able to delete our session data, which is part of destroying a session;0799

but the thing we haven't done is: we haven't been able to eliminate the connection between future HTTP requests and previous ones.0804

And that is what a session does: it links multiple requests together.0810

The reason that they are still linked together is because the session_destroy method doesn't actually destroy that session cookie.0813

Every time we continue to make requests to that website, our browser, unless that cookie is expired,0821

is still going to send that session cookie back to the web server.0826

And so, as far as our web server is concerned, it is still part of the same session.0832

And it is going to link those things together; so session_destroy doesn't destroy the session in that sense, either,0836

in that it doesn't cut that link between previous and future HTTP transactions.0842

For example, we have destroyed our session (this is example-2 again), but if we were to go back and...0850

(we can see that our session's name begins with v1hn; that is the name of our session ID)0860

try to start a new session again, setSessionVar, what we can see is that no cookie was set,0872

and we have continued to pass v1hna (that cookie) to the server, saying it is still part of the same session.0880

And that is a problem, because...it looks like when it created it, it re-created the session file, but what is going to happen is:0891

that would be a problem, because...the reason it re-created it is because this setSessionVar script...0904

what it does is goes ahead and, if the session is already created, creates that session variable.0914

So, it is going to go ahead and re-create that session data file.0919

Maybe...what I was trying to get at...a better example would be: if we go and destroy the session,0923

we can see that we still have this cookie that we are being passed.0932

If we look at the tmp directory, our data file has been destroyed, and so when we refresh this page,0937

we are still passing along that same cookie, except no session data exists for that particular file.0949

In order to sever all ties between past and future HTTP transactions, we must explicitly delete that session cookie.0959

And we do that using the setCookie method: we know that we can delete cookies 0969

by setting a cookie with the same name of the cookie we want to delete with an expiration date that is in the past.0972

And there are two built-in functions to PHP that can help with destroying a session cookie.0984

One is called sessionName, which is going to return the name of sessions, which as we know is also the name of session cookies.0988

And by default, that is PHPSESSID.0994

And we use that method to load the name of the cookie that we are trying to destroy,0998

because maybe in different scenarios...this is a configurable option, so it could change.1002

Maybe somebody just, instead, decided to have session name equal to just SID.1008

That is going to allow us to load the appropriate name of the cookie to destroy.1021

Then, there is a method called sessionGetCookieParams, which allows us to get parameters of a cookie,1024

such as its domain and path, because also, when we are deleting a cookie, 1029

we have to know the domain and the path for that particular cookie.1033

We need to know the name of the cookie, and then domain and path, in order to successfully delete it by setting its time into the past.1037

In our new version, version 3, setSessionVar and getSessionVar are the same.1045

However, in our destroySession, it has been updated.1051

We start the session, as we know that we need to do.1056

We have deleted any session data, and now we are going to delete the session cookie.1059

So, what we do is: we load the parameters for the particular session cookie, using this sessionGetCookieParams method.1064

And then, what we do is make short variables for all of the parameters of the cookie that we are going to be deleting.1072

We load the name of the cookie, which we use the sessionName method to do.1079

We are going to set the expiration of the cookie to expire an hour in the past, so that is going to effectively delete it.1083

We load the path of the cookie to make sure that, when we call the setCookie method, 1089

we are deleting the cookie and have the path matched, so that it actually deletes the cookie.1093

And then, we also are getting a domain, so that the domain of the cookie we are deleting is going to match, so we will be able to delete it.1099

Then, we simply call the setCookie function with the name of the cookie, its path, and its domain1107

that we have been able to extract by calling this sessionGetCookieParams method.1114

And then, we are also going to set the expires, which is going to set it to expire in the past.1120

When that gets called, that Set-Cookie header is going to get sent.1125

The cookie is going to be destroyed; then we are also going to call session_destroy, 1129

which is going to delete the data on the server after the script has ended.1133

And again, if we try to output the username session variable, we are not going to be able to do that, because it has been unset1138

Up here, when we deleted all the session data by setting _SESSION equal to the empty array.1145

So now, if we go and look at our new version, example-3, and delete any session cookies,1150

if we call setSessionVar, it has been assigned the ID in Set-Cookie 58k7.1161

So, remember that--that is the start of our session ID.1169

And we go to getSessionVar, where we are able to output the username method.1172

And just to refresh my memory, 58k7 is the beginning of the name of our session ID.1178

We look in our tmp directory; we can see that we have a 58k7 data file.1185

Now, when we click on...1191

Also, one other thing to note is that, if we look at our cookies currently, we have a 58k7 session cookie; so note that.1194

Now, when we click on destroySession, it is going to do those three things.1206

It is going to delete all our session data, so that we are not able to output that username variable.1211

It is going to delete the session cookie, and if we look at our HTTP header, we can see that it deleted the cookie.1216

It set PHPSESSID equal to deleted, and it set the cookie to expire in the past.1226

We have deleted the session cookie, and then, if we look at our tmp directory, we have also deleted that session data file.1231

It was 58k7, and if we look back, that file no longer exists.1237

So now, we have essentially, effectively ended our session.1243

We have deleted all the session data, so it is not available in the rest of the script.1246

We have deleted the session cookie, so that any future HTTP requests aren't linked to the session that we have just ended.1250

And then, we have also gone ahead and deleted any session data on the server associated with that session,1256

so that those server resources are available for future sessions.1261

And this is just a review of the steps that you need to properly destroy a session.1268

First, you need to call session_start, because first of all, you need to call that before you can call session_destroy.1273

And it is also going to give you access to the _SESSION superglobal, which is going to allow you to perform step 2,1279

which is to explicitly delete any session data stored in _SESSION.1284

And the easiest way to do that is just to set it to the empty array.1288

We have explicitly deleted the session cookie by calling the setCookie function and setting the session cookie to expire in the past, which will effectively delete it.1292

And then, we have destroyed the session data on the server by calling the session_destroy method.1305

Let's say that our session is not properly ended.1313

Let's say we did part of it--we have unset all of our session variables, and we have deleted our session cookie; but we forget to call session_destroy.1316

Well, what that is going to do is: that means that that is going to leave our particular session data file on the server.1325

And what happens is: in PHP, regardless of the expiration of a particular session's cookie,1333

that session's data file has a particular lifetime associated with it.1340

And it is something that you configure with the session.gc_max_lifetime configuration directive,1344

which is the number of seconds until a session data file is seen as garbage.1351

Even if you have a cookie that a user is passing back and forth to the server, that has a PHP session ID1356

for a session that it was a part of, if this max lifetime has been reached for a particular session data file,1364

then PHP may go ahead and delete that file, and so you don't have access to it.1376

It is another way of managing sessions, in which part of the reason for that is to make sure1381

that your temporary directive doesn't get filled up with all these sessions that were never effectively ended by calling session_destroy.1386

After this set amount of time, PHP considers a session data file to be garbage.1395

And PHP has what is known as a garbage collector process (and that is a term used in programming) to free up memory.1402

And what it does is: it periodically runs, and will remove any session data files that have been marked as garbage.1409

And so, what that does is allows any session data files for sessions that have gone on for too long,1415

and may not have been effectively destroyed, to keep from using up all of your server resources.1426

There are two other configuration directives: session.gc_probability and session.gc_divisor.1432

And they are advanced configuration directives (and in fact, all of these are) that we are not really going to get into the details of.1439

But basically, they describe how long it takes until a file gets marked as garbage.1446

And then also, these two describe what are the chances that that file is going to get deleted at the end of its lifetime.1451

It may continue to last for a little longer than its lifetime, depending on how these are set.1459

But they are all in the name of deleting any session data files that have gone on for sessions that no longer exist.1464

For example, if we go back to our destroySession script in our last example,1473

let's say we delete our session cookie, but we leave out the session_destroy method.1482

If we go back and re-run this example (let's delete any session cookies), and we set the session variable, and we view it;1490

we can see that we have created a session that starts with session ID nouha.1503

If we go and look at our tmp directory, we can see a session data file nouha.1509

Now, when we call destroySession, we can see that our cookie has been deleted by looking at the setCookie method.1515

So, our session cookie no longer exists, so our HTTP requests are no longer linked together.1523

However, if we look back at our tmp directory, we can see that this nouha session data file still exists,1530

because we didn't call session_destroy, and that is the purpose of session_destroy.1536

What that means is that eventually, there are default settings in php.ini that are going to know when that file is considered garbage.1540

And I think the default is about 24 minutes, or something like that.1549

And what it is going to do is check in 24 minutes; and if that file still exists, it will go ahead and delete it.1553

And that eliminates the problem where all your server memory or hard disk space1557

would get used up by sessions that were never properly destroyed.1564

Even if you do delete that cookie, if you don't call session_destroy, that data file isn't going to be deleted.1569

And so, that just talks about how the session data files also have a limited lifetime, as well.1574

In general, though, it shouldn't be something you should worry about, if you always call session_destroy when appropriate when destroying a session.1582

For the homework challenge, I want you to extend the homework challenge solution you made for lesson 25.1589

We are going to be adding a logout script to our application that is going to destroy a user's session.1595

We are going to say, "OK, when you have logged out, your session is over."1604

For example, if you were at a website where you go and log in, it might say your name at the top of each page.1607

And then, when you log out, it no longer does; that is effectively ending your session.1611

We are going to mimic that in our application by creating a script called logout.php.1616

We are going to add a link to logout.php on the members-only page, so that when we are viewing the members-only page,1621

we can click on that, and it will allow us to log out.1626

And in logout.php, at the top of the script, I want you to perform the four steps that are needed to properly destroy a session,1629

which are, again: Call session start. Delete all the session variables.1638

Delete the session cookie. And then, call session_destroy.1642

Then, if the session is successfully destroyed (which it should be, assuming that all these methods have been followed),1645

output a message that the user has been successfully logged out.1651

And then, provide him or her a link back to login.html.1655

If it wasn't successfully logged out, output an error message.1660

And again, assuming that this was done right, you shouldn't have to output that error message.1663

The way that you can test that a user is logged out is by verifying that the username session variable1668

that the user set on login.html is no longer set.1674

And again, that is how we checked to see if a user was logged in before: by just testing if the username session variable was set.1680

And so, you want to employ that test again.1692

And what you can do is: I want you to test your completed solution by logging into the site,1697

going to the members-only page, and then clicking on the Log Out link.1702

When you are on that logout page, one thing I want you to note is: note the SID of your session cookie.1707

By using Firebug, you can look at the cookie header and see what your session ID is.1713

And then, click on the link back to login.html.1717

And when you go back to login.html, I want you to log back in to the site and verify that you see1720

that a new session cookie with a different SID has been set.1726

And you will see a Set-Cookie header in Firebug; and what that is going to show you is that1730

you have successfully destroyed your session, and that you have just deleted your session cookie,1734

so that now, when you log in again and that session_start method is called, a new cookie is generated.1738

Also, verify that the session data file associated with your old SID that you looked at on logout.php has been erased.1744

And then, you also see that a new session data file, matching your new session ID, has been created.1752

One note as far as testing goes: one thing that is helpful in testing is to make sure that you delete any localhost cookies1758

stored by Firefox, before testing your solution, so that you don't run into problems1765

where you are not actually starting a new session when you first log into your website.1769

And the way, again, to do that is: if you go to Firefox, and then Options, if you click on the Privacy tab,1778

Remove individual cookies, you can search for any localhost cookies.1784

And here there are none, but you would just select them and click to remove them.1789

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.1795

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing development of our web application,0005

incorporating what we learned in our last lesson about properly destroying a session.0009

Specifically, we are going to be introducing one new topic, called the __autoload function, which is a special function in PHP0014

that is going to make it easier to load class definition files and eliminate some include statements from our config.php file.0021

And then, we are going to go over version 13.0 of the web application, which is the new version of our web application,0029

which is going to incorporate what we learned in the last lesson about how to properly destroy a session,0035

which includes deleting the session data explicitly, and then also deleting the session cookie.0040

First, one thing to note is that, as your web application grows, and you add classes to it, 0047

you are going to have an increasing number of include statements--for example, in our application in our config.php file, 0053

in order to include all of the class definitions that you have; and that can become tedious after a while.0061

And in fact, if we go and look at our config.php file for the last version of the web application,0066

we can see that we have all of these includes here for all of the different classes that we have created.0077

So, as we add more and more classes, we are going to have more and more include files.0082

And it can become cumbersome, and it would be a nice way to automate that.0086

What PHP allows you to do is create a function that starts with two underscores, called __autoload.0089

And if you define that in a file somewhere in your application, and include the definition of that function,0099

PHP is going to use that file to automatically load a class.0105

So, whenever it reaches a point in your code where it is instantiating a new instance of a class,0108

what it is going to do is call the __autoload function.0116

It is going to pass it the parameter that this __autoload function takes, which is the name of the class that it is trying to load.0119

For example, if it comes upon a statement "item variable equals new Item"--let's say we are creating a new Item object--0126

what PHP is going to do is call the __autoload function automatically with the name of the class, Item.0138

And then, what we do is define this __autoload function so that it knows how to take this name0149

that was passed to the function, and be able to appropriately load that class.0155

That way, we can get rid of all those include statements, and instead we just have this one __autoload function.0161

If we take a look at the __autoload function that we have created for this new version of the web application,0166

it is stored in a new library file called classLIB.php, which contains functions related to classes.0172

In this case, it is just one particular function.0179

And here, you can see that we have defined the __autoload function.0182

And what it does is: it takes one parameter, which is a string, which is the name of a class to load.0186

And then, what it does is: we have coded it so that it calls an include statement to include the class definition file that PHP is requesting.0193

And the reason we define this function is because we know where our class is located.0206

In this case, they are loaded in the class directory that is specified by our CLASS_DIR constant.0212

In addition, the names of our class files are the name of the class, followed by .php.0217

So, maybe somebody else's application might have a different way of naming classes.0223

For example, some people call their classes item.class.php.0227

So, this would be the spot where you would be able to adjust your code so that PHP is going to be able to properly load these classes.0233

Again, this function is just your way of telling PHP how to find these classes and load them.0240

We have added the __autoload function, as mentioned, to this class library that we now include as part of our web application.0247

And in addition, if we look at our new version of config.php, and we look at the source code,0256

in the last version (this was version 12.0), we have all of these include statements for all of these different classes:0268

Cart, CartItem, Customer, Department, and so forth.0274

Well, in our new config.php file, we have eliminated all of these include statements for all of these different classes.0278

And instead, we have one include statement that includes our classLIB.php that defines that __autoload function.0285

So now, instead of having to list all of these different class includes, we just include the function definition for __autoload.0291

The other nice thing about that is: if we don't automatically...we include this config.php file on every page in our web application;0297

so, every time we load a page, it goes and loads all of those classes that we had listed in our previous version.0304

Because we have an include statement before it, it automatically goes and gets that class definition file and loads it.0312

It is going to load all of the classes; it may be, on our page, we only need a Department class or an Item class.0316

It is going to go ahead and load all of those other class definitions that it doesn't necessarily need on that page.0323

The nice thing about this __autoload function is that it is going to reduce some of that overhead,0329

because you are not going to be including files you don't need, because __autoload will only be called when a particular class file is needed.0333

The other thing that we have done is created a new class called SessionManager, 0341

which is part of the reason for introducing this __autoload function now, 0346

because the number of classes is continuing to grow in our application.0350

This SessionManager class has been created to handle all of our session-related tasks.0354

For example, starting a session, adding variables to a session, and then now 0362

what we are going to learn about in today's lesson, destroying a session--are all combined to this one class.0367

If we go and look at our SessionManager class, and look at the documentation for it,0373

we can see that it has a couple of different methods.0385

It has a constructor; it has a destroy method, a getVar and setVar method (which are methods used to add a variable to a session),0387

and then an inSession method, which is a way of being able to test whether a particular variable is currently set in your session.0395

If we look at the constructor...0403

The way we use this class is: in any script where we want to access sessions, we instantiate an instance of this SessionManager class.0405

Now, when the constructor gets called, it automatically calls this session_start method.0415

So, just by instantiating that class, we have gone ahead and started a session.0419

And then, we can do things, for example, like call the setVar method; and we could pass it a name and a value.0423

And what that does is goes ahead and accesses our _SESSION superglobal, which is now accessible,0430

because once this object has been created, session_start has been called, and it allows us to add variables to the session data.0435

It has a getVar method, which is the analog of the setVar method, which returns the value of a particular variable.0443

We specify as a parameter the name of the session variable we are trying to get.0453

And here, what it does is: it returns null if that session variable doesn't exist, and it returns the value of that session variable if it does exist.0457

The way it does that is makes use of this inSession function, which is also defined in this class,0467

that just tests if a variable exists in the current session or not.0472

And it does that in the same way that we did before.0476

For example, in some of our homework and lecture examples, we use the isset method to test for the existence of a username session variable.0479

By testing, we use that as our way of saying, "OK, a user has been logged in."0487

This provides that same sort of functionality: we provide the name of the session variable to inSession that we want to see if it exists.0492

And it returns the value of the isset method.0498

Now, the one nice thing about having this class to manage all of the session-related functionality0502

is that, if we have any problems with our _SESSION superglobal, or we are having problems with our sessions,0508

we only have to look in one spot, because anything related to sessions is all handled in this class.0515

Instead of having, for example, in our previous version of the web application, a session_start method call,0520

and then accesses to the _SESSION superglobal, and then also directly setting session variables 0528

and having them spread throughout all different versions of the code,0536

we can put it all in this one class, and then we call these class methods.0539

And so, if we have a problem with accessing, for example, a session variable, we only have to look in the one spot, which is our SessionManager class.0543

Now, one of the main reasons that we have added this SessionManager class is because it has a method called destroy,0551

which is going (now that we have learned in our last lesson how to properly destroy a session) to succeed in doing that.0558

And I am going to go ahead and open the source code for it, because it calls a private method, which doesn't show up in the documentation.0565

We have our destroy method, which, when you call it on a SessionManager object--the first thing it does 0574

is deletes any session variables, and does so by setting the _SESSION superglobal equal to an empty array.0581

It destroys the session cookie (which--we learned that just by calling session_destroy, that doesn't happen).0594

So, we have an explicit method that destroys that session cookie, which I am going to show in a second.0599

And then, to ensure that the session data stored on the server is destroyed, we call the session_destroy method.0604

The four steps that we learned about to destroy a session (calling session_start, deleting the session data,0612

deleting the session cookie, and calling session_destroy) all happen in this one class.0618

When the class is instantiated, that calls the session_start method, which is step 1.0623

And then, this destroy method completes the other three steps.0627

If we look, we have a private method here called destroySessionCookie, which is used to destroy the session cookie.0630

And it performs the functionality that we saw in the last lesson.0636

It gets the parameters of the session cookie for the current session; it retrieves the name of that session cookie;0640

and what it does is calls the setCookie function that sets that session cookie to expire at a time in the past.0646

When this destroy method is called, it calls destroySessionCookie, which calls the setCookie function.0655

So, when the user gets their HTTP response back for this page, the user is going to know0661

that the cookie is expired, and therefore the session is going to be officially ended, and it will be properly destroyed.0665

That is what we use this new SessionManager class for.0672

What we have done is updated our viewCart.php and checkout.php scripts, which are scripts that use session functionality.0678

And we have updated them to use this new SessionManager class for all session-related tasks--0688

For example, starting a session with session_start, and then loading and saving our Cart object to and from the session data.0693

If we go and look at our old viewCart script, for example, we have an explicit call to session_start.0705

And the way we load our cart is by calling the isset method on the _SESSION superglobal,0712

and then setting the session variable equal to the Cart session variable if it exists, and if not, creating a new Cart.0717

Well, in our new script, the session_start is replaced by instantiating this new SessionManager class.0724

It is going to implicitly call that session_start method.0730

And then, we load the class by making use of these methods that SessionManager provides.0733

For example, to test whether the Cart object exists, we call the inSession method on the SessionManager object.0738

If it exists, we return the value of that cart variable, using the getVar method that we defined in our SessionManager class.0746

And otherwise, it returns simply a new Cart object.0755

Similarly, in our last application, part of what we do when we view our cart is add and remove items from the cart.0759

So, we need to update that Cart object in the session.0765

Previously, we did that by directly accessing the _SESSION superglobal within our viewCart script,0768

so that now, that direct access...I'm not sure whether this is updated...this is incorrect...0775

it should be updated so that it calls the SessionManager setVar function...I don't know why that wasn't corrected.0785

So, in our new version, what should have been done was: now, when we save our session to the cart,0809

instead of directly saving it to the _SESSION superglobal, we call this setVar method0814

that we just talked about that is a part of the SessionManager class.0818

We provide the name of the session variable we want to set (which, for our particular application, is cart).0822

And then, we provide it the Cart object that we want to associate with that session variable name.0826

In checkout.php, we have replaced, at the beginning, the session_start method and the loading of the session cart0833

that uses direct access of the _SESSION superglobal, in the same way that we did in viewCart.php,0840

by creating a new instance of the SessionManager class, calling the inSession method to test if the cart session variable exists,0846

and then, if so, setting this cart variable equal to the session variable cartObject, using the getVar method of SessionManager.0854

Now, we don't save anything in this checkout form, so we don't call that setVar method.0866

But the thing that we do is: after an order is completed, the session functionality that we do is:0871

we destroy a session, or we try to end a session.0875

In our previous version, when we ended the session, if an order was successfully completed,0878

we simply just unset the cart variable by directly accessing the _SESSION superglobal.0887

What that effectively did was eliminated the cart, so that when we go back to viewCart, it no longer appears.0893

In our 12.0 example, if we were to add an item to a cart, and then we were to go to checkout,0899

two things to note are that...actually, let's refresh this page, so we can see our session ID;0931

if we look down here in Firebug, we can see that our session cookie is called jcp04.0938

So, if we look at our tmp directory, we can see that we have this session data file that starts with jcp04.0944

When we go ahead and submit this form, and click on Complete Order, we can see that that cookie still exists.0952

We haven't received a Set-Cookie response header from the server erasing that cookie.0976

So, as you can see, this was from the request going to this page;0986

but if we refresh this page, or even, for example, if we go back to viewCart,0991

we can see that we are still passing this session cookie, so our session cookie hasn't been deleted.1003

We can also see that our cart is empty, because we called that unset method on it.1008

But because we didn't also call session_destroy, if we go and look at our tmp directory,1013

we can see that that jcp session file is still there.1015

Well, in our new version, when we go to checkout.php and we successfully check out,1020

instead of just unsetting the session variable, we call the destroy method on SessionManager,1027

which is going to delete all the session variables, delete the session cookie, and then destroy the session data on the server.1034

So, in our new application (I'll delete any session cookies we have), if we add a winter jacket, for example, to our cart,1041

and go to check out, we can see that our new session is eg5dr.1053

So, if we look in our temporary directory, we see a data file for that eg5dr.1060

If we go ahead and check out again, now when we complete our order, we can see a couple things.1065

If we look at our Host headers, we can see that the cookie has been deleted.1084

We can see that there is a setCookie method that was called that deletes that session cookie.1088

If we look at our tmp directory, we can see that the data is no longer there.1094

It was called eg5dr; we can see that that data file is no longer there.1099

And in addition, if we try to view our cart again, we can see that the cart is going to show up as empty.1103

And that is because we have successfully deleted that session data.1109

And so, that is making use of that destroy function that we have created.1113

One thing to note is that, if we look at our destroy method, if any of these steps would have been eliminated--1119

for example, we commented out this destroySession here--that cookie would still remain.1132

If we commented out session_destroy, the data would still remain on the server.1136

We need all of these steps to properly destroy a session, and that is how we make use of this function on checkout.php.1141

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1150

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

Today's lesson is a rather exciting lesson, because we are going to be writing an introduction to databases,0005

which is going to lead us down the path towards integrating a MySQL database with our PHP application,0010

which is one of the main goals of this course.0014

As part of our lesson today, we are going to be discussing a concept known as flat files,0018

which is a way of maintaining data for a particular web application.0022

We are going to introduce the concept of relational databases, which is what MySQL is.0027

As far as our relational databases go, we are going to talk about what a table is, and some of the properties of columns in relational database tables.0033

We are going to introduce something you may have heard about before, called SQL.0043

It is a structured query language; we are going to talk about what that is, and how it is used to work with databases.0047

And then, we are finally going to finish up with a rather important topic, called primary keys, 0055

that describes some types of data that are going to be included in our tables, 0060

and then provides some primary key examples to emphasize the point.0065

In general, a database is just an organized collection of data that you can access.0071

You can add information to it, and then you can search it, or in database parlance, you can 'query' it, to find out information.0076

In our web store, we have had a database that we have kind of referred to as a database,0084

but not so much specifically calling a database.0089

And what we have been doing is storing all of our data in text files, which are often referred to as flat files.0094

So, it is considered a flat file database.0101

And these text files that we have--items.txt and departments.txt--contain all of the data about the items and departments in our store.0104

And it is essentially our database.0111

If we look at items.txt, for example, what it does is, as we know, describes the item ID of a particular item;0114

it has its name, its cost, its description, image extension, and so forth.0123

And so, we have been storing all of this information in a database that is just composed of files.0128

Well, there are a couple of problems associated with using flat files to the database that relational databases are going to help to solve.0136

First of all, it is typically slow to access and add and search information from text files.0143

As mentioned, they are difficult to search; and to do things such as updating a file is difficult, as well.0151

For example, in our current application, when we update a department, what we are doing is copying all the file out;0158

we are searching for the row that we need to update.0166

We update that row, and then we rewrite all of those rows back to the file, 0168

which is not a very efficient way to do things, and can take time, and is difficult.0171

Additionally, concurrent access to flat files can be a problem.0179

If you have maybe two web users that are logged in at the same time that are trying to add an item to the store, for example,0182

they both have to have access to that items.txt file.0189

And so, we haven't talked too much about it, because our relational database is going to take care of that;0192

but you have to worry about such things as file locking issues, 0197

so that multiple people can access the file at the same time without overwriting each other's data.0200

Our relational database is going to help to solve some of these problems.0206

Our relational database is a different kind of database, and it stores data, and relations0212

between the different pieces of data in the database, in structures called tables.0220

It stores things in tabular format.0227

And what is known as a relational database system, or RDBMS, is a system that provides an interface for managing and using a relational database.0232

A relational database is comprised of all the tables that contain the information in the database.0243

The RDBMS provides additional features on top of that.0248

It provides an interface for accessing those tables, adding and deleting information in the database.0252

It also provides ways of providing security on them.0258

It provides things to allow concurrent access to the data.0263

And so, MySQL is a relational database management system, and so it provides these additional features.0267

So, not only are we using a relational database, but we are using this management system on the outside 0274

that provides this nice interface that allows us to do different things.0278

RDBMS's solve many of the problems of flat files, one of the first being that they are faster than flat files for both storing and retrieving data.0284

We talked a little bit, just a minute ago, about searching for data in a flat file.0292

But actually, when we need to look up an item in the store, we need to go through line-by-line,0297

each line in the file, looking for a particular item.0302

Relational databases are made for doing that in a fast and efficient manner, so it is going to increase the speed with which we can look things up.0305

Additionally, part of the service that relational database management systems provide is: they handle concurrent access automatically.0312

So, they allow multiple users to connect to the database to read and write.0321

And they ensure that one person's changes don't overwrite another person's changes.0325

In our flat file database system, if we really wanted to ensure a system that allows multiple people to access it at the same time,0330

we would have to write our own code to do that.0338

And it is rather difficult to do, and we basically would have to manage it on our own.0341

So, using a relational database eliminates us from having to even worry about concurrent access, as the database handles that automatically.0345

The other thing that and RDBMS provides is typically a privilege system for controlling access to the data.0353

So, for right now, our flat files can be accessed by anybody that has operating system permissions on those files.0359

Well, what you can do with the RDBMS is have fine-grain control over your data.0367

You add users to the database system that restricts who can access what parts of the data--0372

For example, who can access certain tables of data, who can perform certain operations,0383

who can add things to the database, who can only query from the database, and so forth.0387

And the nice thing about that is: again, this is something that is built into the database management system.0393

So, it is not something that we have to implement.0399

If we wanted to implement that on our own, outside of the operating system privileges that provide basic access control for files,0401

we would have to implement that in PHP and validate a particular user and say,0410

"OK, this user can access that file; this user can update this file."0413

Well, the relational database management system does that for you automatically.0418

One thing to note is that you will hear me say RDBMS, or relational database; and I sort of use those terms interchangeably,0423

which is a common thing to do; so just so you know, any time I refer to an RDBMS or relational database, I am referring to the same thing.0431

I will refer to a MySQL database, and in this case I am referring to the whole database management system,0439

which provides these things--like the privilege system, facility for concurrent access, and so forth.0445

Also, for the remainder of this course, when I just use the term 'database,' I am referring to a relational database,0452

because that is what MySQL provides, and that is what we are going to be using for the rest of the course.0458

Relational databases store data in structures called tables, which organize data into rows and columns.0465

If you have ever used a spreadsheet before, it is pretty much the same exact thing.0473

What you have is defined columns that describe the types of data that rows in the table should provide.0478

And what each row is--it is known as a record.0487

And it is a set of values that provide values for all of the different columns.0492

It would make it easier to explain if I had a concrete example.0499

Let's say we have a table called Customers, which is used to store the names of all our customers for our fictitious web store.0501

We can define a couple of columns: one column is called firstName, and we are going to use that to store the first name of our customer;0509

we have a column lastName that stores the last name, and a column middleInitial that stores the middle initial of the customer.0516

So then, what we have is: that defines the structure of this table.0522

It defines the different columns, and the different data that is in this table.0527

And then, what we do is add rows to the table that represent these real-world objects, these customer objects.0531

Then, customers have a first name, a last name, and an initial, and so for each row, we provide values for the first name, the last name, and the middle initial.0537

For example, this first row of the database represents the customer Joe T. Smith.0545

We can add as many of these as we need to for each customer in the store.0550

And that is how the table organizes data: rows provide values to the data defined by the columns.0554

Now, columns in tables have at least two properties.0565

The first one is a name (which is what we saw in the last one: we had the firstName column, 0571

the lastName column, and the middleInitial) that can identify the data that is stored there.0575

They also, like PHP (we have variables that have data types, integers, floats, and so forth)--columns have an associated data type with them.0582

For example, for our firstName column (we are going to learn more about the specifics later),0591

that would be a string data type, because it contains text.0600

So, that first column in our database has a name equal to firstName, and then it has a data type associated, which is string, 0604

which means that every row in that table, to store a value in this firstName column, for example--you need to provide a string for it.0611

You provide Joe, for example, and so forth.0620

You can have other things, like numbers; maybe you would have a birthDate column.0624

And there is a special data type for dates and times, in which you could store Joe's birth date, for example.0631

Columns have both names and data types associated with them.0641

Now, I want to talk about SQL; this is something you may have heard before.0648

It is definitely something that is directly associated with relational databases.0651

What it stands for is Structured Query Language, which is not particularly important, as much as what it does.0657

And what it is: it is a language to work with relational databases.0664

It can be used in several different ways.0669

It can be used to define the structures in a database and the tables in a database.0671

For example, it might say, "OK, I have this database that has five tables."0675

"One table represents customers; it has these columns. One table represents orders and has these different columns," and so forth.0679

It provides a way to, in database terms, insert, update, and delete data in the database.0688

You can insert rows in the database; you can delete a row from the database.0695

For example, you could delete a customer from the database.0699

And you can update it; for example, maybe you have an item, and you want to update its price.0702

You could update that in the database, using what is known as a sequel update command.0705

And by the way, you can refer to it as 'sequel' or SQL; people call it different things.0710

The other thing that you can do with SQL is query (in database terms, that is another name for requesting or searching a database)0716

the database for specific pieces of information.0726

For example, you might say, "Give me the address of customer Joe Smith."0729

Maybe you have that stored in your database, and then you run this query--this SQL command--on this relational database.0733

It understands that command, and then it is able to provide that information back to you.0740

The other thing that SQL provides is several standard data types for data that can be stored in a database.0744

As mentioned, the columns in tables have data types associated with them.0753

For example, our firstName column contains string data, and our birthDate column would contain date/time data types.0758

Well, SQL provides a couple of different data types for all of Integers.0767

It provides a couple of types for floating-point numbers, a couple of different data types related to strings, 0774

and a couple of data types related to storing dates and times.0781

And we are not going to talk about the specific data types now; but as we build up our web application0785

and start introducing SQL commands, we are going to talk about these data types specifically, as they come up.0791

I want to finish up this lesson with an important topic known as primary keys.0800

One of the main things that you do with a database is: after you add information to it, you query the database; you request information from it.0807

We have to have a way to look up data in the database: primary keys are a means of doing that.0813

For example, let's say we want to look up customer Joe Smith's address in the database.0820

Maybe he is a row in this Customers table.0826

Well, in order to do that, we have to have a way to uniquely identify Joe Smith.0830

And a piece of data that can be used to uniquely identify a table row is known as a primary key.0835

For example, we couldn't necessarily use the name Joe as a primary key, because you might have other people named Joe in your database.0844

So, when you query the database and say, "Give me the address associated with Joe,"0850

it is not going to be able to uniquely identify it.0854

What a primary key is: it is something that has to be unique.0859

For example, something in the real world that is unique is a Social Security number.0861

Each person only has one Social Security number, so that could be a piece of data that you could add.0866

It can be a column that you could add to your database, socialSecurityNumber.0871

That is not something you would probably want to do, but it is just as an educational example.0874

And what that would do is: you could look up a database and say, "Give me the row associated with Social Security...."0878

And if we know that that is Joe's Social Security Number, the database can return the information associated with Joe.0885

It is a way to uniquely identify a particular row in a table of the database.0890

And what you can do is note columns of a table as primary key columns.0896

What that says: for example, if we had a Social Security number column, we would tell the database, "This is a primary key column."0902

And what that means is that, for every row that is in that table, a value can only exist one time.0908

For example, you can't have two rows that have the same Social Security number; that defeats the point of a primary key.0917

And so, what you do is define it as part of the database (and we are going to learn more about how to specifically do that0924

when we create tables) to say, "This column represents a primary key, so ensure that a row isn't added0928

that tries to add a value for this primaryKey column that is a repeat of another one in the table."0936

When we talk about a table's primary key (which is a term you will hear used), 0945

we are referring to the column whose values serve as the primary keys for the rows.0950

For example, if we were using socialSecurityNumber, we would say, "The primary key of table Customers is socialSecurityNumber."0956

Another unique thing is that books have ISBN numbers, which uniquely identify a book.0965

If we had a table of books, we could say, "The primary key for that table is ISBN."0969

And we might have a column in the table called ISBN, along with maybe the name of the book, and so forth.0974

And so, the key thing to note is that there is a one-to-one correspondence between a primary key and a row in the database.0983

You can't have one primary key value that links to multiple rows in a database.0989

In that case, it wouldn't be a primary key.0994

For example, to explain a little further what we were just talking about, let's say we had our three customers in the database from before.0998

But I have changed some of the data here.1006

So, let's say we wanted to look up Joe Smith; let's assume this column wasn't here, for now--we just had our three columns, as before.1007

If you want to look up Joe Smith (maybe we had additional columns over here that had address information,1019

so we want to find Joe's address), we say, "OK, give me Joe Smith's address."1025

Well, how could we do that? We couldn't say, "Give me Joe's address," because there is another Joe in the table.1030

Well, let's try his last name; we could say, "Well, give me the person whose last name is Smith--their address."1036

Well, that doesn't work, because we have a Jane Smith also.1041

Likewise, we have a doubled-up middle initial, so we couldn't say, "Give me the address of the person with middle initial D."1044

However, if we add our primary key column, socialSecurityNumber, which is a one-to-one correspondence1053

between a person (or a customer) and that ID, we could say,1060

"Give me the address of the customer with Social Security number 123456789."1065

And then, our database is going to be able to go and look it up in this table, and find this exact row right here,1071

and pull up any of the information in that row, as needed.1077

One thing to note is that this is called a table schema--it is a way of describing a table,1082

and often you will see a table described by its column names.1089

For example, this table has four columns: firstName, lastName, middleInitial, and socialSecurityNumber.1093

Typically, when you see column names listed, if it is a primary key, it is underlined.1098

That is something that you might see out there in literature and documents on the Web1102

that you come upon that talk about the structures of relational databases.1108

If something is underlined, that typically means it is a primary key.1113

Another option (because let's say we don't want to store Social Security numbers, which you probably don't,1117

for privacy reasons)--another thing that you can do--is just to randomly generate a unique ID every time you add a user to the database.1122

For example, when we add Joe T. Smith to the database, we can assign him the number 1.1131

When we add Jane D. Smith to the database, we can assign her the number 2.1137

And we have defined a new column here; instead of Social Security number, we have defined a primary key column called customerID.1142

What that means is that each row in this particular table has to have a unique value for it.1149

And then maybe we add Joe D. Simpson, and we assign him number 3.1156

The way you can do that is: you can manually do it--you can check the database, and one way to do it is just continually incrementing a number.1159

So, we could say, "What was the last person added to the database--what is their customer ID?"1167

Well, Joe Simpson had a customer ID of 3; "OK, when I add a new user, I am going to create a new user with customer ID 4."1171

So now, that ensures that each row has a unique customer ID, and it has a primary key to associate with it.1184

When I want to look up Jane Smith, I will say, "Give me the customer information associated with customer ID 2."1190

And so, this customer ID doesn't have a real-world analog, whereas Social Security number does.1198

There are some things in the world that you can use to model real-world objects, 1203

like Social Security numbers and ISBN numbers, that can be used to uniquely identify things.1207

But oftentimes (and what we are going to be using in all of our examples in this course),1212

we will just be using randomly generated numbers, because that is something that we can ensure will always be unique.1216

One thing that you want to note is that if, let's say, you don't use something like this,1223

where you are continually incrementing a number each time a person is added to the database.1228

You want to make sure that, if you don't do that, and you define a primary key column like Social Security number,1234

that that is something that will ensure that any future users added to the database won't have multiple variables.1239

We know that each person (at least in the United States) has an individual Social Security number.1246

So, we know that any time we add a new person in the database, that Social Security number is not going to come up.1251

So, that reason is why we couldn't use something like last name, because there might be another Smith we add to the database.1257

And so, when you pick your primary key column, you want think about the future, as well,1266

and make sure that this is something that is always going to be unique, even in the future.1271

That ends today's discussion on the introduction of databases.1277

Thank you for watching today's lesson; I look forward to seeing you next time.1281

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be introducing the concept of file I/O, or file input and output.0005

Specifically, we are going to be going over what file I/O is; and as part of that discussion, 0013

we are going to be talking about what file permissions are, which is something you may be familiar with,0017

especially if you have used a Linux or UNIX platform.0023

We are also going to be going over the different methods used to read from files.0026

The first method we are going to talk about is called fopen, which is a built-in function of PHP.0032

And as part of that, we are going to provide a discussion of specifying file paths to that function,0037

and also the different access modes that you can specify to the function, 0042

that describe whether you want to open a file to read or write, for example.0047

We are going to go over the concept of file pointers, which is very similar to an array cursor,0051

which allows you to read or write from a certain point in a document, based on where this particular pointer is.0057

And then, we are going to go over a couple of other methods that relate to working with files.0064

fgets is a way of reading a single line from a file; feof is a function that tests if your file pointer is at the end of a file.0070

And we will explain more about that, and then we are going to go over the fclose method,0082

which is the analog to fopen, which is a way to close a particular file.0085

And we are also going to talk about the trim function, which is useful when working with files.0090

A file I/O, or file input and output, refers to reading from and writing to files in a file system.0098

PHP fortunately provides a number of built-in functions for doing so.0107

And in order to perform file I/O, there are typically three steps involved.0112

The first step is: you open a connection, or you open a particular file.0118

Then, what you do is perform any read or write operations that you need to on that particular file.0122

And when you are done with those operations, you close the file.0128

And so, we are going to, as we go through this lesson, walk through each of these different steps.0132

One thing to note about opening a file is that, when you open a file, we will be learning that you need to specify0139

whether you intend to just read or write from that particular file.0146

Now, we are going to talk about file permissions.0153

And like I said, those of you that use UNIX or Linux systems are more familiar with this than Windows users.0154

But in order to read or write from or to a particular file, you need to have the appropriate permissions on that file.0162

For example, to read from a file, you need to have what is known as read permissions on the file.0169

To write to a file, you need to have write permissions on the file.0174

And what these are, are permissions that are set by the particular operating system, on the system that you are using.0178

So, for our local development environment, it is going to be Windows's permission system.0184

If you are developing, if you are using a web host, they typically use a Linux server.0188

It is going to be dealing with Linux's permission systems for read and write permissions.0195

One of the things to note is that not having the proper file permissions for a particular file is one of the most common errors 0202

in trying to do file I/O with PHP--if you are trying to read from a file (and you don't have read permission), 0209

or write from the file (if you don't have permission to write on the file).0215

Now typically, with an operating system, the way permissions work is: they are associated with a particular user account.0220

For example, in Windows, when you log onto your computer, that is your user account.0227

And you have certain read and write permissions for different directories and different files.0231

Typically, you always have (for example) read and write permissions for all of the directories and files within your user directory.0236

When using PHP, one thing to note that you may encounter as a problem is that PHP, when the PHP Interpreter runs on your server,0244

it typically runs as a PHP user account, or as a web user account.0257

So, you have to make sure that the account associated with the PHP Interpreter0261

(and this is something that you may be able to change, or maybe it's something that you will have to talk to your system admin about)--0265

that that user account has to have a proper permission set to read or write for a particular file.0270

If PHP is trying to open a file for reading, whatever user that PHP Interpreter process is running at 0277

needs to have permission to read or write from that particular file.0284

The first step in working with a file in PHP is to open the file for reading or writing.0290

And you do that using what is known as the fopen function.0295

Again, it is a built-in function of PHP, and it takes two required parameters.0299

The first one is the name and the path to the file that you are going to be opening.0304

The second is what is known as the read and write mode with which to open the file.0309

So, as mentioned, when you open a file, you have to let PHP and the operating system know whether you intend to0314

just read from the file, write from the file, or do both.0318

If fopen on a particular file is successful, it returns what is known as a file handle.0323

And what a file handle is: it represents an open connection to that particular file.0329

In PHP, a file handle is one of the special PHP data types (the other one being null) that is known as a resource data type.0335

Basically, it is a data type that refers to an external resource (in this case, a handle to an open file).0346

Another example of a resource data type might be a connection to a MySQL database.0354

If fopen fails, it returns false, and then it generates an E_WARNING-level error.0360

So, that is something that we are going to talk a little bit about working with--how to handle that error when you use the fopen function.0367

And this is a key function, because a valid file handle is needed by all of the other PHP file I/O functions that we are going to be dealing with.0374

because when you call up a function (for example) to read a line from a file, you have to pass it a valid file handle.0383

And that valid file handle means that it's a handle to an opened PHP file.0389

So, this is really a key function.0397

If we go and look at php.net and the documentation for the fopen function, we can see, 0400

it has these two required parameters: file name and mode (mode being the read/write mode that you use to open a particular file).0406

And if you look down here, you can see: with mode, there are a number of different options that you use to open a file.0418

You can open it to read, open it to write...we are going to go over that a little more in a second.0423

File paths: as we saw, the first parameter to the fopen function is a file name parameter.0433

And you have to provide a path to the file that you want to open.0438

That can be a relative path or an absolute path, depending on the situation.0442

A couple things to notice about how to specify the paths: in Windows, you may know that paths are typically separated by the backslash character.0450

And on a UNIX system, they are actually separated by a forward slash character.0459

So, when you are specifying the path to a file in the fopen function, on a Windows system, 0463

it lets you use either forward slashes or back slashes to specify the path.0471

And in order to specify a backslash within a PHP string literal, you have to escape it; so you will notice that,0479

for each backslash, you actually have two backslash characters.0485

On a UNIX system, which is maybe what your web host is going to be using, file paths are denoted with the forward slash character.0490

One thing to note is that, for the maximum code portability, you should always use forward slashes, even when working on a Windows environment.0499

For example, if this was specified...let's say this was just a path right here...this path is a relative path because it uses forward slashes.0507

If we move the application that uses this particular path from a Windows machine to a UNIX machine, the relative path would still work,0517

because the forward slash character can be used for both Windows and UNIX.0527

Now, that said, if we had instead used the backslash character to specify the path (and here I am eliminating the escape character),0532

now if we move our application to a Linux system, it is not going to be able to find that file in a relative path, because of the / character.0548

File access modes are the second parameter to the fopen function, and are a 1- to 2-character string0560

that tells PHP whether you want to open a file for reading, writing, or both.0568

And there are a couple other different options that you can do, as well.0572

One thing to note is that, in order to open a file for reading or writing, you have to have the proper permissions for that, as we had talked about.0577

You can request PHP, for example, to open a file to read; but if you don't have read permission on that file, you are not going to be able to do that.0585

And if we go back and look at the documentation for fopen, you can see: in the function documentation--the function reference--0592

there are a number of different modes that you can specify.0600

You can specify the character r (which is what we are going to be using in today's lesson)--a lowercase r that says 0602

you are just opening the file to read, and you want the file pointer (which we are going to get to) to be placed at the beginning of the file.0607

We can use the w that says we are going to open the file for write.0615

There are modes for appending to the end of the file, and creating a new file, and so forth.0618

We are going to talk more about those when we get to the lesson on writing to files.0624

Let's go take a look at some sample code that we have.0632

There is a file called fopen.php; and we are going to use the fopen function in a couple of different ways to show how it is used.0635

We are going to be opening a file that is in the data directory of the directory that fopen.php is contained in.0646

So, fopen.php is in one directory; then, within that directory, there is another subdirectory called data.0659

For example, if we look at our lecture 3 examples, we can see that we have an fopen file;0665

and then, within that, there is a subdirectory called data that contains a file called stocks.txt.0671

This is the file that we are going to be trying to open.0677

And stock.txt, if we actually look at it, is a little terse; and we are going to explain more about that when we get to a future example,0681

but it basically is our way of representing the current stock for different items in a particular store.0690

For right now, we are just going to work with opening the file.0698

The first way we are going to do that is by using a relative path.0700

So, we specify a string called relPath that specifies a relative path to stock.txt.0703

And as you can see, it is in the data subdirectory where this fopen.php file is located.0712

And then, here we call the fopen function; we pass it the path name, or the path to the file, which is a relative path in this case; 0720

and we pass it the access mode r, which says we want to open this file for reading.0726

Then, as we mentioned, if fopen does not work, what it will do is return false, saying that there was an error opening the file.0732

We test; it says that if file handle is false, we are going to output an error message that says, "There was an error opening the file."0741

And if it successfully opens it, we are going to output a message that says, "The file was successfully opened for reading."0748

Down here, we have another example that does the same thing, except we are going to use an absolute path and the fopen function.0754

So, instead of providing a relative path, we are going to provide an absolute path.0763

In this case, we define our absolute path using the SERVER ['DOCUMENT_ROOT'] superglobal array value.0766

And then, we are adding this specific path to our stock.txt file.0777

And as you can see, the same function call is made, except we use this absPath variable, which has an absolute path.0783

And again, we are going to test if there was an error opening the file; and if so, we are going to output an error message.0791

And if not, we are going to say that the file was successfully opened for reading.0796

If we go and load this script in our browser (go to fopen.php), we can see a couple of things.0801

We can see fopen using a relative path; and what it does is says, "The file" and it shows the relative path to that file "was successfully opened for reading."0809

So, we were able to open that file correctly.0817

And then, down here, when we use the absolute path, our output is--0819

and this is the absolute path to stock.txt--it says that file was successfully opened for reading.0823

We can see here an example of using both an absolute and a relative path with fopen.0829

There is a third example in this file, in which we try to generate an error using fopen, to show how it handles an error.0835

For example, we are going to try to open a file called stock.csv, which is an extension used for comma-separated value files.0843

You might have heard of it; it doesn't matter if you have or haven't.0855

But what you will notice is that, in our data subdirectory, in which fopen.php is located, there is no stock.csv file.0859

So, when we go to open this file, we should get an error from PHP.0871

And so, we should say, "There is an error opening this path."0875

And if we go and look at the end of the script (let's refresh it, just to make sure), we can see: at the bottom here,0877

it says, "warning: fopen on stock.csv failed to open"--the file doesn't exist.0885

And then, we have our output message that says, "There was an error opening stock.csv."0894

And one thing that is typically used here: because we have generated our own error output message here,0899

we don't really typically want this PHP warning to be output; it is kind of ugly, and it doesn't provide a good user experience.0907

So, we are going to make use of the error suppression operator, which is the @ symbol.0916

We are going to prepend that to the fopen function that is going to generate this error, so that, when we reload our page, 0924

the PHP warning is not going to be output; and we are just going to have it output our own error message.0932

And any time we are going to be using fopen in this course (and as you will pretty much see any time you see fopen used),0937

it will be prepended with that error suppression operator, so that, if there is an error opening that file,0942

it doesn't output the ugly error message to your user's output.0948

So now, something I want to talk about is a file pointer.0956

It is kind of like an array cursor, which we learned about in the introductory course.0960

What it is: it is a cursor that is used to keep track of the current character being accessed in the file.0964

For example, if we have a file down here that has these three lines (which is a number of different characters, 0972

separated by hidden new line characters here), when we are reading to or writing from a file, 0978

we read to or write from a file based on the location of the file pointer.0986

For example, when we open a file using fopen with the r access mode, it opens the file for reading,0990

and it places the file cursor here, at the beginning of the file.0996

So, when we go to read (for example) the first four characters from this file, it is going to read from the current file pointer.1000

It is going to read up to here--the first four characters.1009

Now, for example (and there are different functions for moving this cursor around) that the file pointer was actually down here, before this i character.1012

Now, when we read four characters, it is going to read these four characters here: i, s, space, and l.1021

So, the file pointer is what is used to read from a file.1028

And also, if we are going to write to a file, when you write to a file, it is going to write to wherever that current location of the file pointer is.1031

One thing to note is that, sometimes, you will hear file handles referred to as file pointers; and that is commonly used.1040

In this course, we are going to distinguish between a file handle and a file pointer to make it easier to understand,1047

so that there is less confusion, because often, they are both referred to as file pointers.1054

So, for this course, we are going to use file handle to refer to the handle, or the connection, to an open file,1060

and then a file pointer to refer to the cursor that you use to access data within a file via reads or writes.1067

The first function we are going to introduce for reading from a file is called fgets.1077

And what it does is: it reads the contents of the current line of a file.1082

So, wherever the file pointer is--whatever line it is on--it reads out the contents of that file.1086

And if that pointer is in the middle of the line, it just reads from wherever that pointer is until the end of the line.1091

The other thing that it does is: after it reads the contents of the line, it advances the file pointer to the beginning of the next line.1098

Let's take a look at the fgets function in action.1106

We have a file called fgets.php, and we have a similar code to what we had in the last example, fopen.php.1109

We define a relative path to this stock.txt file; we open the file for reading.1117

We are using the r access mode, which is going to place the file pointer at the beginning of the file, so it will be at the very beginning of the first line.1124

You can see, we have the error suppression operator here, which is going to suppress any errors1131

(for example, "PHP can't find this stock.txt file").1136

If there is an error opening the file, we output an error message; if not, we move forward.1139

And then, what we do is call the fgets method.1144

And the fgets method takes at least one required parameter, that is the handle to the file that you want to read the current line from.1147

When we call fgets and pass it fileHandle, because fileHandle hasn't been used by any other (for example) read or write functions,1156

and we open the file with this r access mode, when you call fgets for the first time on a file handle, it is going to read the first line of the file.1165

So, what we do is call fgets on fileHandle and store the contents of that first line in this variable line.1174

And then, we output "contents of the first line are" whatever is stored in that variable.1179

If we go and view this script in our browser, when we go to fgets, we can see the output.1185

It says "contents of the first line is 100011."1192

And if we go back and look at stock.txt, we can see that that is the contents of the first line in the file.1197

That is how you use fgets to read a line from a file.1204

Now, typically you don't just want to read the first line of a file; you want to read multiple lines in a file, or even all of the lines in the file.1210

And one thing that is commonly used with fgets is another function called feof.1216

And what that allows you to do is test to see if the file pointer is at the end of the file.1224

For example, if you want to read all of the different lines in a file, and then stop reading from that file when you reach the end of the file,1227

you use this feof to function to let you know to stop reading lines, because you are at the end of the file.1235

And just so you know, eof stands for "end of file"; and it is commonly used to refer to when you have reached the end of a particular file.1241

If we go and look at a new piece of code called feof.php, what we are going to do is loop over all of the lines in that stock.txt file and output them.1252

Here, we have defined the relative path to the file; we have opened it using fopen.1269

And then, what we have done is created a loop that says, "As long as feof on this file handle on this file that we have opened is not true,"1276

meaning that it is not the end of the file yet, "it is going to continue to go through this loop."1287

And what it does is: when it enters into this loop, the first time, it is going to evaluate this test condition.1292

feof is going to return false, because it is not the end of the file; so not false is true.1298

We are going to enter the while loop, and the first thing we are going to do is get the current line in the file.1303

This, the first time we go through this, is going to get the contents of the first line in the file.1309

Then, what we are doing is simply outputting the line number of the file with the contents of that line.1313

And in order to do that, we have defined a lineNum variable, which is sort of like a loop counter that we are going to use to keep track of the line number.1319

Then, after it has output that line, it is going to increment the line number.1327

It is going to go back to the test condition of the while loop, and it is going to say, "Are we at the end of the file yet?"1331

In this case, because our file (as you have seen) has three lines in it, it is going to say, "No, we are not at the end of the file."1336

So, we are going to run the loop again, and we are going to go ahead and read the line and output it.1341

In this case, it is going to happen several times, and it is going to output each line of the file.1346

So, if we go and look at the results of this...we go to feof.php...we can see that it outputs line1=1000:5.1352

It outputs line 2 and line 3; and also, you can see, it tried to output a line 4.1362

You can see that it actually entered this loop a fourth time, but when it tried to output line, there was nothing there.1369

Well, the reason that happened is because in stock.txt, there are four lines, because at the end of this third line,1376

there is actually a new line character, which makes it line 4.1384

So, when feof is testing this file to see if it's at the end of the file, after it reads this third line, it is going to come down here1387

to this next line, and it is going to see that it is not the end of the file, because there is still a new line there.1398

And it is going to read the contents of that new line.1402

In this case, the new line has nothing on it, which is why it outputs nothing.1405

That is one thing you will have to be careful of, either by not including a new line at the end of your data files,1410

or testing for that condition (which is something we are going to show in an example in a minute).1415

As mentioned at the beginning of the lesson, there is a 3-step process for file I/O in PHP, or pretty much in most programming languages.1426

You open the file; you perform any read or writes that you need to on it; and then you close the file.1434

In this slide, we are going to talk about fclose, which is the analog to fopen; it is used to close the connection to an open file.1439

The way you do that is: you pass it a handle to an open file as its parameter, and what happens is that fclose goes ahead and closes that file.1446

Now, some people don't always close a file after they are done using it, but it is a recommended practice that you always1455

close any files that you have opened in your code, and also do so as soon as you are done using a file.1462

And part of the reason for that is something known file locking.1468

Typically, on a computer, only one process or program can access a file at the same time.1473

So, if you have a file open--if you have opened it, and you are doing a bunch of processing on it, and stop processing;1479

and you go off and do a bunch of other stuff, but haven't closed it; then any other program on the computer1485

trying to access that file is not going to be able to.1489

So, that is one of the main reasons for always closing a file when you are done with it, and doing it as soon as possible--1492

so that it is free for any other process to use.1498

Let's take a look at another code example called fclose.php.1502

And what this does is completes this 3-step loop.1507

We open our file using fopen, the same file as before.1513

We loop over each file, outputting it (we read each line of that file, and then output that line's contents).1516

And then, here you can see, we use the fclose method.1522

We have just finished using the file for all the reads that we need to, so we want to close it right away.1525

fclose returns true or false, depending on whether it was able to successfully close the file or not.1531

Based on that return value, if it was successfully closed, we are going to say "the file relPath was successfully closed."1537

If not, we are going to say there was an error closing it.1544

If we go and look at fclose.php, and we view it, we can see it outputs different lines of the file.1548

You will see here, it still outputs line 4, because we have that new line in the file.1555

And it is going to output the message at the end: "The file ./data/stock.txt was successfully closed."1559

And so, that is an example of using the fclose method.1567

Now, we are going to take a look at a little more real-world example in a file called currentStock.php.1571

What it is going to do is read this stock.txt file, and it is going to output for the user the current stock of each item number in the store.1576

For example, in this file, the way stock.txt is set up is: the first part of each line is an item number of an item in this fictitious store, for example.1588

And then, a colon is entered; and then after the colon is the current stock of the item.1600

And we put each item and its current stock on a new line in our stock.txt file.1609

For example, this file states that there are five items with item ID 1001 currently in stock.1615

It is out of stock of item 1002, because the quantity here is 0; and it has 24, currently, of item 1003.1625

What we do in this currentStock.php script is: we open for reading this stock.txt file.1636

And what we do is: we are going to loop over each line of the file, using this feof text function.1646

At each line that we are going to go to, we are going to read that line, using the fgets method.1653

What that is going to do is return (for example, when we read the first line) 100011.1659

Then, what we want to do is separate that information out into something useful.1666

We want to separate it out into an item ID and the current stock.1668

So, we are going to use the explode function and specify that we are going to be using the colon as the delimiter.1672

And we are going to say, "Take this string that we read from the file and separate it into parts, based on where the colon is."1680

And it is going to generate an array, and the first part of that array, or the value with the 0 index of that array, is going to be the item ID.1689

The value with the next index, the 1 index, is going to be the current stock.1696

Here, we do a little test that says, "If the length of lineArr is not equal to 2, then continue processing the next line."1703

And this our way of correcting for when we reach this fourth line here.1711

Instead of outputting the stock for this line, that is for an item that doesn't exist, when it reads this line, 1717

and it runs explode on it, there is no colon; it is not going to return an array that is of size 2.1728

So, we are going to just say, "Skip over processing it."1733

And that way, that empty line doesn't get output.1735

Now, if the array does equal 2 in size, then we are going to extract the item ID and current stock amount from the array.1741

And here, we are just creating some short variables: we are going to say, "Item ID is equal to the value of the array at the 0 index,1749

and the current stock is equal to the value of the array at the 1 index."1755

And then, we are just going to output a line that says "Item ID has so-and-so items in stock, based on what was in the file."1760

We are going to do that for each of the items in the file.1769

And then, what we are going to do is close the file using the fclose method.1772

And if there is an error, we are going to generate an error message that says "There was an error generating the code."1776

If we go and look at this file, currentStock.php, we can see that it read over the file, and it said:1786

"Item 1001--there are 5 in stock; item 1002--0 in stock; item 1003--there are 24 in stock."1794

And so, this is the output of this file.1804

And one thing you will notice is that it has put "in stock" on a separate line in this page.1805

And if we look back here, and we look at our string to output, we don't have a new line or a break in there.1812

And so, what is happening is: an extra new line is getting into there, being added to that.1822

And because we are enclosing this output in the pre tag, it outputs the text as is.1828

So, if there is a new line character, it outputs it as a new line, or makes it look like a break.1836

If we look at the source code here, we can see that, after 5, there is a new line (let me blow this up) in the code.1840

And you can see, "in stock" is on a separate line.1851

Similarly, when we process item 2 after 0, we can see that a new line is output.1855

The reason for that is: if we look at stock.txt, each of these lines has two parts.1860

It has the item ID, and then a colon; and then it has the current stock.1867

But also, there is a new line character here (which allows us to put the second item on the next line).1875

So, when explode runs on this line, it is going to return, as the second element, 5 and a new line character 1882

(which is why that new line character is going to show up).1891

And so, now, we are going to talk about a way to get rid of that new line character.1894

PHP provides a built-in function called trim; and it is often used; and what it does is strips any white space from the beginning or end of a string.1901

And it is often used to strip new line characters from lines read from a file.1910

So, what we are going to do: if we go back to currentStock.php, here, when we get the current stock from this lineArr1915

that we have created using the explode method, we are going to run the trim function on that array value.1929

And what that is going to do is strip that new line character off of that current stock,1936

because when it reads this line (for example, the first line), it reads 5 and then a new line.1944

Well, now, when it gets that string here by lineArr index 1, and we run trim on it, it is going to get rid of that new line.1950

So, all that is going to be left in that string is 5.1959

So, if we save this, and we go and look at the file again, we are going to see that now that new line doesn't appear.1961

And the string appears as we had written it, with "in stock" being on the same line.1970

So, it says "item number 1001 has 5 in stock."1973

And if we look at our source code, we can see that none of those (let's blow it up) new lines after the current stock appear anymore.1977

And so, typically, any time we are going to be reading stuff from a file, we are going to be running the trim command on it, as well.1988

So, we are going to do that for itemID.1995

In this case, it is not going to matter; but in some cases it does, so just as a good practice, when we read from a file,1997

and we use (for example) this explode method, we are going to trim any data that we get.2004

If we just run it again, everything is going to look the same; but that is just good practice.2010

For the homework challenge for today's course, I want you to do something similar to what we did in today's lecture.2018

I want you to create a data file called users.txt, where each line is a comma-delimited string2023

(in our example in this lecture, we used a colon-delimited string)--2029

a comma-delimited string that represents the first name, last name, and email address of the user.2033

And so, for example, one user in this data file might be represented like this: 2040

Tom, Stevens (this is his first name and his last name), tstevens@gmail.com (it's his email address).2045

You won't see it here, but there will actually be a new line character.2053

You will go to a new line and add another first name, last name, and email address for a particular user.2055

So, go ahead and populate this file, users.txt, with several fictitious users, just for use in this example.2062

And then, what I want you to do is: from PHP script, open this users.txt file; read each line; and then, after reading each line,2070

output the name of each user and the email address of each user.2079

You are going to have to make use of that explode command that we use in this thing.2085

And also, I want you to make sure that you use all of the functions that we used in the course today.2089

Use the fopen function to open the file; fgets to read a particular line; feof to test when you have reached looping over the lines in a file;2094

fclose (which is important) so that you close a particular file; and then use the trim function, so that you don't have that error2105

that we saw when we read a line from our file in today's lecture, where it adds an extra new line to a string that it reads from a file.2112

And test that example out on this text file that you create, and then see the name and email address output for each different user.2121

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2132

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be continuing our discussion of databases by getting to learn more about the details of the MySQL database system.0005

Specifically, we are going to be talking about what MySQL is; it is a relational database management system.0013

We are going to talk about some of the properties and features of MySQL.0019

We are going to talk about a program that comes with a MySQL distribution called the MySQL Monitor,0023

which is a way of connecting to a MySQL database and issuing SQL commands on it.0028

We are going to go over the steps that it takes to connect to a MySQL server.0034

And then, we are going to show how to be able to do that, using this MySQL Monitor program we are talking about.0039

And then, we are going to learn about the GRANT command, which is a way to create users on a MySQL server.0045

And users are a means of the database restricting access to particular parts of the database.0051

We are going to learn about how to create users using the GRANT command.0057

And then, we are going to walk through the setup of a user account for our PHP scripts,0061

so that our PHP scripts will be able to access our store database.0066

And then, we are going to go over a required homework, and it is a little bit different from your usual homework.0070

It is going to be a required homework, because the steps that you will be going through--you will need to go through these steps0075

in order to set up your MySQL database, so that when we continue web application development,0082

you will be able to connect to a database that is properly set up.0089

What is MySQL? Well, it is an open-source relational database management system.0095

At the back end, it is a relational database, and what it does is (because it is a relational database management system):0102

it provides some features and an interface on top of the database in order to properly use it.0108

It is commonly used with PHP applications; that is probably one of the reasons why you are taking this course:0116

PHP and MySQL are used together very often.0122

One of the things about MySQL is that, like most relational database management systems, in operates using a client-server model.0125

The database runs as a server, and then you have clients that connect to that server and then issue commands.0134

And what MySQL does is contains multiple databases; a MySQL installation can contain multiple databases,0143

each of which can contain multiple tables; and we learned about tables in our last lesson.0155

That is the way to store data in a relational database.0160

A MySQL server can have multiple databases; for example, you might have a couple of different web projects,0165

and you might create a different database (which is just a logical structure for a bunch of tables)0169

which might contain multiple tables; so you can have multiple databases with multiple tables,0174

each related to different projects, and each of the tables containing different information.0179

One thing you will notice is that I have been referring to it, in a way, as a MySQL server.0186

Because it runs in this client-server model, you will typically hear the terms MySQL database and MySQL server used interchangeably.0191

And that is what we are going to be using in this course, also.0199

Sometimes I will refer to it as the server, sometimes as the database.0202

But essentially, when I say that, I am just referring to the MySQL relational database management system as a whole.0205

So, when you are connecting to a MySQL database, you are connecting to this database management system0212

that runs as a server, that gives you access to the relational database.0217

One of the features that MySQL provides is a user privilege system, which controls access to that MySQL server.0222

It allows you to set up permissions for different user accounts to restrict access to certain databases and to certain tables.0229

For example, you could set it up so that a particular user can only access one particular database.0237

That is something that might be common on a web hosting.0243

If you have hosted on a web host before, you might only have access to a specific database.0247

So, they might tell you that, when you connect to a MySQL server (which we are going to learn more about in this lesson),0252

you have to use a particular database set up for your account.0258

And it is a way to restrict access to the database, and then also to different operations on the database.0261

For example, you might create a user account that can only run searches, or queries, on the database--0267

whereas another user account might be able to add information to the database.0273

When MySQL is first installed (as is the case in the XAMPP installation), it contains a root user account.0280

And it contains that account with no password initially.0287

And what that allows you to do is to initially log in to the server, and then create additional user accounts.0290

And then, what you do is build up the security of the system from there.0296

What we are going to be doing is logging in as the root user in order to create our PHP user account,0300

which is an account that we are going to give privileges to, 0307

so that we can use that account to access our MySQL database from our PHP scripts.0310

As mentioned, MySQL runs in a client-server model, and the database itself acts as the server.0318

And what you do is connect to it using clients.0324

A PHP script, for example, would fall under the category of a client.0327

It is something that can connect to the database and run queries on it, which is the ultimate goal of this course:0330

we are going to be learning how to use a PHP script as a client to connect and run queries on the database.0335

Well, there is also a program included with the MySQL installation by default, called the MySQL Monitor.0342

And it is just a command-line program that allows you to connect to a running MySQL server, and then issue SQL commands on it.0349

In XAMPP, the MySQL program is called mysql.exe, and it is located in the bin subdirectory of the mysql directory of the xampp root directory.0360

For example, if we were to go to our xampp directory (which for this course, we have set up in our Windows User directory),0374

and we go to xampp, and the mysql directory, and then the bin directory, you can see a bunch of different files,0383

a lot of which are executables, and you can see the mysql.exe program.0390

What that is: that is that client (and we are going to be learning how to use that) that allows to connect to a MySQL database.0395

The way you use the MySQL Monitor program is by issuing a command that looks like this.0404

You specify MySQL, which is the name of the program, mysql.exe (you don't have to include the .exe, however).0410

And then, it has a couple of parameters, or options, that you can pass to it0416

that describe how you should connect to the particular database.0422

In that command that we just saw, there were a couple of command options.0428

The first one is specified by -h, followed by hostname in single quotes.0432

What that does is specifies the hostname, or it can be an IP address, of the MySQL server that you are trying to connect to.0438

The MySQL server is running on a computer somewhere.0446

For example, if you host your website at a web host, it might be running on a server somewhere on the network of your web host.0450

In our particular example with XAMPP, we are going to be running the server on our localhost, so we will be running on the same machine.0458

So, when we try to connect to MySQL, we are going to be specifying hostname as localhost.0464

And again, it is a hostname that represents a particular computer that contains the MySQL server that you are trying to connect to.0472

The -u command option was followed up by the username, or the user account that you want to connect to.0485

So, when you issue that command, you replace that with the username of a valid user account that has been set up on that MySQL server.0493

One of the things--for example, when you get set up with a web host, if you are using a shared hosting plan,0502

they might tell you the hostname of the MySQL server (maybe it's mysql1.hostexample.com--maybe that is the hostname of the server).0507

And you would specify that with -h.0526

And they might tell you that your username to connect to (they have set you up a user account) maybe is your account number.0527

Maybe it's 78967; and what -u does is: that is a command option that allows you to specify what user you want to connect to the server as.0533

Host specifies which server you want to connect to, and then -p is an option that tells the program that,0547

when you try to connect to the server, you want it to request a password from you.0554

After you specify the -p option and you run the command, it is going to ask you to enter your password,0558

which you can do, and it will be masked, like the password forms on web pages, 0563

so that anybody looking over your shoulder can't see the characters that you are typing.0570

One thing to note is: if you leave out the -h option when you run this command, by default it uses the value localhost.0574

Because we are going to be running this on our local machine from a Windows command prompt, we will be able to leave out that -h option.0583

How do we go ahead and connect to a MySQL server with XAMPP, using this MySQL Monitor?0595

Well, the first thing that we do is (actually, I'll stop it, because it has been running) open up the XAMPP control panel.0600

And underneath the section for starting and running Apache, there is one for MySQL.0607

And you can go ahead and click the Start button, and what that does is gets that MySQL server up and running on your local computer.0614

And then, what we do is: because it is a command-line program, we are going to be using the Windows command prompt,0624

which some of you may or may not have experience using.0630

We are just going to use some basic command-line commands to be able to use our MySQL program.0633

Most of the commands that we are going to be learning are commands you issue once in the program.0643

You open a Windows Command Prompt, and for those of you that don't know how to do that,0649

on Windows 7, when you click on the Start menu, you can go and type in the search box0653

(and I am doing this off to the side; you won't be able to see it) cmd.exe.0658

And what is going to happen is: Windows will show you the cmd.exe program that you can select and start.0670

And when you click on it, it is going to open up a window like this that shows a command prompt.0679

It shows you the current directory that you are in.0683

Well, in order to be able to run the MySQL Monitor program, we have to switch to the directory that that program is in,0686

so that when we run this MySQL command here, the command prompt knows where to find that program at.0693

The first thing we do is change the directory to this bin directory of the mysql directory of our XAMPP installation.0701

And we change that directory; and the way you do that is using a command called CD, which stands for Change Directory.0708

And we are going to use an absolute path, so in our Windows Command Prompt, you type CD, and then a space,0713

and then the name of the directory that we are trying to switch to.0720

And in Windows, remember that directories are separated by back slashes.0724

In our case, we go to our user directory, which is in Users/(your username) in Windows 7.0729

We are going to go to the xampp installation folder, the mysql folder, and the bin folder of that.0738

And that is going to give us access to this MySQL program.0746

And now, what we want to do is connect to the server, using this root account that we said is set up by default.0748

And as mentioned, the root user does not initially have a password, so when we are prompted for a password,0754

by issuing this command here, we just hit Enter.0759

And what it is going to do is start the program.0762

So, we can type mysql, which is a command to run the program, and then we pass it some command-line parameters.0764

We are going to go ahead here (even though we mentioned we don't need to) and specify that we want to connect0771

to the MySQL server running on the hostname specified by localhost, which is the local computer.0776

We are going to specify the username, using the -u command.0782

So, we are saying -u, and then space, and then the username we want to connect as.0786

We want to connect as root, and then we want it to prompt us for a password, so we can authenticate ourselves.0789

So, we enter -p, and when we hit Enter, it is going to prompt us to enter a password.0795

Because root doesn't have a password, we can simply hit Enter as a blank password.0801

It is going to connect, and now we are connected to the MySQL Monitor.0804

And what you can see is that it outputs a little information.0808

It says, "Welcome to MySQL Monitor," talks about the version of the MySQL server you are connected to...0811

And then, down here, it has the MySQL Command Prompt, and it is kind of like its own command prompt that allows you to run the SQL commands.0818

As far as using this MySQL Monitor, when you are at the MySQL Command Prompt 0831

(which is the word mysql followed by a greater than sign), you can enter in different commands.0836

You can enter in different SQL commands.0841

One thing to note is: like statements in PHP, you must terminate your statements with a semicolon.0843

One other thing that you can do is have commands that span multiple lines.0851

One of the things that we will see is that, as we start learning more about databases,0854

we are going to see that we are going to be entering commands that are quite long.0859

So, it is often helpful to space them on different lines to make them easier to read.0861

The way you can do that is to simply hit Enter.0865

For example, if I wanted to type a fake command on multiple lines, I just hit Enter.0867

And what you can see is that it adds a little dash, greater than sign.0874

And that is a signal to you, the user, that it is still expecting you to enter some more of the command.0879

So, I might type 'rest of command,' and then to execute the command, you finish it with a semicolon and simply hit Enter.0885

Now, when I do this, we are going to get an error, because it is not a valid command.0892

But that is how you run a command, and how you have it span multiple lines.0895

And then, when you are done using the MySQL Monitor, you just type exit, and that is going to exit you out of the program.0900

And it brings you back to the command prompt.0906

As mentioned, there is a privilege system that is built into MySQL that allows you to restrict access to parts of the database.0911

And there is a GRANT SQL command that is used to grant privileges to users.0918

And it can be used to create a database user, as well as grant them privileges.0925

And the command has the format that follows this format here.0929

It has a couple of keywords, GRANT, and TO, and IDENTIFIED, and BY.0937

And those are parts of the command that you have to specify.0942

Typically, in SQL, oftentimes you will see, in an SQL command, that any special keywords are required by a command0947

(for example, GRANT) are specified in all capital letters; though it is not necessary to do that, that is often the convention.0956

With this GRANT command, we have a couple pieces of information we need to provide.0964

We need to provide the types of privileges we want to grant.0968

And we specify (we are going to learn more about these in a second) what we want to grant these privileges on.0973

For example, we might say we want to allow this user that we are creating to have only query or select privileges on table Users,0979

which means they can only run select queries (which we are going to learn more about) on a particular table called Users.0989

We are saying, "Grant privileges on these particular database objects."0995

And here is where we specify our user: we are saying, "Create a user account with the username username" (enclosed in single quotes).0999

And that is where you would substitute what username you want to create.1008

And then, you say @, and then a hostname provided in single quotes.1012

And what that does is says that that is the hostname that that user is allowed to connect from.1016

So, for example, one of the things that we are going to be doing is creating a PHP user account.1021

I'm not sure why that is not erasing.1032

And the way that we specify that would be like this.1038

And what that is saying is, "Create an account" on the server that we are connected to, that you are issuing these commands to,1045

"called PHP user," and that PHP user is going to be able to connect to this server only from the localhost computer.1051

You could specify something else, like maybe a specific IP address that says 1059

that the PHP user can only connect to this server from a computer with IP address 192.68.1.2, for example.1071

We are going to be specifying localhost, because all of our scripts are going to be running on the same machine as our MySQL server.1079

And then, after you specify the username and the host that that user can connect from,1084

you can specified the IDENTIFIED BY keywords, and then include the password 1088

that you want that user to log in with, within quotation marks.1093

The underlined values that are in this command here are values that you must provide to the command, and refer to some different things.1099

The privileges are the type of privileges that you want to grant to the user.1109

It might be...for example, we might grant all privileges, which gives them access to do everything they want to in the database.1114

It might be that they can just view contents of the database; they can just insert contents in the database.1120

The privilege system is an advanced topic, and it is sort of beyond the scope of what we are going to get into in this course.1127

But you can definitely look at the MySQL documentation, if you are curious about that,1133

and find out more information about the different types of privileges that you can grant.1136

The objects parameter of this SQL command specifies the database objects on which you can grant particular privileges.1141

And we will see on the next slide that you can...let's say we were going to use GRANT all1152

(and all is a word that you can use, that says, "Give all privileges to this particular user.").1158

You might grant all privileges on all of the tables in a particular database.1165

Or you might give all privileges to the user for all tables and all databases.1169

The other parts of the GRANT command that were underlined are username 1179

(which is the username we want to create for the account that you are creating);1184

hostname specifies the host from which the user is allowed to connect (so it is the host they have to connect from;1189

it might be a particular IP address; it might be a hostname);1197

and then, password is just the password that you want to create for the account.1200

Now, the objects, as mentioned, specifies database objects that privileges are going to work on.1206

So, if we say GRANT all (which means grant all privileges) ON, and then the form that this objects parameter takes is shown here...1211

Basically, you provide a database name, followed by a period, followed by a table name.1227

And so, what that allows you to do is: if you specify a particular database, you can say, for example...1233

maybe we have a database called PHP, and we have a table in it called Users; this is saying,1240

"Grant all privileges on the Users table in the PHP database," and down here we would create the rest of the command:1246

TO so-and-so user, with a password.1254

Now, what you can do is use wildcard characters.1257

Instead of having PHP.Users here, we could say PHP.* (in this case, if * is to the right of the period, it means all tables).1259

So in this case, we are saying, "Grant all privileges to this user on all tables in the PHP database."1269

And it can work the other way, as well; you can do *.*, which says, "Grant all privileges to" whatever user you select "on all tables in all databases."1276

And so, that is the format that it uses: it has the database name and a period, 1292

followed by the database table, or wildcard characters, if you want to specify those.1296

Now, what we are going to do is walk through running a GRANT command that is going to create a PHP user account1303

that we could use to connect to MySQL from our PHP scripts.1309

We are going to be creating a username called phpuser that is going to be able to connect to the MySQL server from the localhost.1314

And the reason it is from the localhost is because our script, our web server, is running on the same server as our MySQL server-1321

at least, in this XAMPP distribution that we are using.1328

We are going to be issuing this command here, and we are saying, "Grant all privileges."1332

And 'all' gives you full permission to do whatever you want in the database.1339

That is not necessarily a secure way of doing things: you want to be as restrictive as possible.1344

But for educational purposes, we are going to grant all privileges.1351

So, that is going to allow us to experiment with different SQL commands.1355

But that is definitely not something you would want to do in a production environment.1357

And so, we are going to grant all privileges to our PHP user that is going to connect from the localhost.1362

And we are going to give them all privileges on all databases and all tables in all the databases.1369

Again, that is something you probably wouldn't want to do--to give access to a user to all databases.1375

For example, you might just want to give them access to all the tables in the PHP database.1380

So, this is, again, just for educational purposes that we are going to grant all privileges on all tables,1386

so that we can experiment and learn about SQL.1391

And then, we are going to specify that it is going to be identified by (it is going to have the password) xxx,1395

which--you can put in whatever password that you want there.1400

So, we are going to have you, as part of the homework, run this command on your home computer.1404

And you go ahead and create this phpuser account, and then specify whatever password you would like to have for the phpuser.1409

Again, all is going to grant all privileges to the user, and then *.* is going to specify that it grants privileges on all tables in all the databases.1417

If we go back to our command prompt (and we logged out of the MySQL Monitor program), and we are going to log back in,1429

this time I am not going to specify the -h localhost parameter, because as mentioned, by default it will default to that.1437

I'm just going to type -u and specify that we want to connect to the root user, and we want to be prompted for a password.1445

Just hit Enter when it asks for a password, because again, we don't have a password for the root account currently.1453

And then, what we are going to do is run this GRANT command.1459

We are going to run GRANT; we are going to type GRANT all, so grant all privileges.1461

And I'm going to do it over several lines; as mentioned, just by hitting Enter, it allows you to continue a command on a separate line.1466

We are saying, "Grant all privileges on all tables on all databases to the user we are creating (phpuser)."1473

And we are saying that that phpuser will be connecting from the localhost.1483

And then, we are going to say it is going to be identified by (let's spell it right)...in this case, I am just going to pick the password Educator.1489

And then, finish the command with a semicolon.1500

What we are saying is, "Grant all privileges on all tables in all databases to a new user called phpuser1503

that will be connecting from the localhost that will be identified by (that will have the password) Educator."1510

And so, when we hit Enter, it is going to give you a result that says "query OK," which means that the query went through--1515

or it has called the query, that the command went through, and that it ran OK.1521

And so now, what I want to do is exit out of the MySQL Monitor program 1525

and then just verify that the account works by trying to log back in as this new user.1530

What we are going to do is specify MySQL; this time, I'll specify the host name, because we did create it, so we are connecting from the localhost.1535

Well, this localhost here actually refers to the MySQL server, so you can just ignore that.1548

And then, we are going to specify that we are going to connect as phpuser, which is the name of the new user account we created.1554

We are going to say -p, which says we want to be prompted by a password.1560

We hit Enter; now, we are going to be prompted by a password, and we have a password, which in this case was Educator.1566

So, when I type that, now we are logged into the MySQL server, as before.1571

And we are logged in as phpuser, which has all privileges on all tables in all databases.1575

And so, now we know that that account is set up and worked; and that is what we are going to be using from our PHP script.1581

The required homework for this is to go through and set up what we just did,1590

which is to create that phpuser account, because for the demo web store application that we are creating,1595

in order to be able to run future versions of that, you are going to have to have the database set up.1602

And so, we are going to have you set it up by issuing this GRANT command.1606

The steps, again, are just: start the MySQL database from the XAMPP control panel;1610

you open a Windows Command Prompt, and you switch to the MySQL bin directory, using the CD command, using an absolute path.1616

You go ahead and connect to the MySQL database, using the MySQL Monitor program as the root user.1626

And then, just issue a GRANT command that is going to create this phpuser account1632

that can connect from the localhost, has a password that you choose, and should have all privileges on all tables in all databases.1635

Then, type exit to quit the MySQL Monitor.1645

And then, verify that you have successfully created the account.1650

1) You should see a 'query OK' symbol, assuming the syntax and the command was written in correctly.1652

And it may give you an error, for example, if you leave out a single quote, or there is an error anywhere in your syntax.1658

And it will let you know; so if you get query OK, that lets you know the query went through all right.1663

And then, just to double-check to make sure that everything worked, log out and then log back in1668

as this new phpuser that you created, using the password that you created.1674

And if all goes well, you will be presented with a MySQL prompt that will allow you to begin issuing commands to the database.1679

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1687

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be learning how to create databases and tables.0005

We are going to learn about specifically creating a database, using what is called the CREATE DATABASE command.0011

And as we learned in a previous lesson, the MySQL server, the way it is set up, contains a number of different databases,0017

each of which can contain a number of different tables.0023

We are going to learn how to create a database for our store web application.0025

We are going to learn about the CREATE TABLE command, which, as the name implies, 0030

allows you to create a table within a particular database on the MySQL server.0032

We are going to learn in a little more detail about SQL data types, which are data types for the columns in a table that we will be creating.0038

As we learned before, in relational databases, data is organized in rows and columns.0046

And for each particular column, you can have data values, and they must correspond to a particular data type.0051

We are going to talk about something called column attributes, which in addition to providing a data type 0057

for a particular column in a table that we are creating...we can also specify some particular features of that column.0062

We are going to learn how to create the command used to create the Items table in our database,0069

which we are going to be using for our web store application, to hold all of the information about the items in our store.0074

We are going to go over a couple useful commands that can help you to find out 0079

about the structure of your database and the structure of tables that you have created.0083

And then, we are going to go over another required homework that you are going to need to do to set up this Items table,0087

so that we can connect to it from our web application.0097

A database is created in SQL using the CREATE DATABASE SQL command.0103

It simply is CREATE DATABASE, followed by the name of the database that you want to create, as a parameter; it is a very simple command.0110

And then, MySQL also provides a couple of non-SQL commands that allow you to provide some information about the MySQL server.0119

When you log into the MySQL server, you can type, for example, SHOW DATABASES.0128

And that is going to list all of the databases that currently exist on that MySQL server that your user has access to.0132

And that is a sort of a privilege thing.0138

Now, we are going to be connecting, in this lesson and all of the other lessons, as the phpuser, which is the account we created in the last lesson.0140

And because they have all privileges, we are going to be able to see all of the databases within the particular MySQL server we are connecting to.0153

There is also the USE command that you can issue that you type in at the MySQL Command Prompt that says, 0161

"Use" and you specify the name of a particular database that you want to use.0169

What that does is tells the MySQL Monitor that any future commands you issue are going to be issued on that particular database.0172

For example, if you are inserting data into a database, you won't have to specify (as we will learn,0179

when we learn about inserted statements) both the name of the database and the table you want to insert data to.0186

You will just be able to specify the name of the table, because USE is already going to let MySQL know you are using a particular database.0192

What we are going to do is create our database that we are going to use for our web application, or web store.0199

We are going to call the database advanced_php.0205

And so, what I am going to do is bring up the MySQL Monitor program, which we learned about.0214

And the way you do that, again, is by opening the Windows Command Prompt, and then using this CD command0219

to change to the directory where that mysql.exe file is located (which is the MySQL Monitor client program).0227

And then, we are going to connect as this phpuser account we have created.0246

We type mysql; we don't need to specify the hostname, because we are going to default to the localhost;0251

we are going to be connecting to the MySQL server on the localhost.0256

We are going to be logging in as user phpuser, and we are going to ask it to prompt us for a password.0260

I'm going to go ahead and enter the password that we had set up last time; for this example, we had set up Educator as the password.0269

So now, we can see that we have our MySQL prompt; it shows that we have been able to successfully log in.0276

The first thing we do is run that SHOW DATABASES command that I told you about.0281

And what that is going to do is list all of the different databases that are available on this current MySQL server.0286

We can see that there a number of different databases.0293

Even though we haven't actually created anything, the MySQL database itself comes with its own databases already built--0295

for example, the mysql database; and then, XAMPP does some other things to set up some other databases0307

(for example, some example databases; there is a test database, and so forth).0315

Those are the databases that are currently on this server.0319

Now, we are going to create our advanced_php database: we type CREATE DATABASE 0322

and the name that we want to give to it (which is advanced_php), followed by a semicolon, and hit Enter.0328

It is going to say 'query OK' to let us know that the command was successfully run.0335

And then, one thing you can do is use the up and down arrow keys when you are on the MySQL prompt.0340

And it is going to let you scroll through previously entered commands, which can save you some typing.0347

So, because we typed SHOW DATABASES as our last command, if I hit the up arrow once,0350

it is going to go ahead and populate the command prompt with SHOW DATABASES.0354

So now, when I enter it (oops, it looks like I entered a typo; I typed a 3 by accident), SHOW DATABASES,0357

we can see all of the databases that we had before; but now, we also can see our advanced_php database.0370

So now, any of the future commands we are going to be using, we want to operate on this advanced_php database.0377

So, we are going to type USE advanced_php, and that is going to tell this Monitor client that we are going to be using this database,0384

because in a second, we are going to be creating a table in this particular database.0393

It is going to let you know that the database has changed; you are currently using advanced_php.0397

SQL has a command called the CREATE TABLE command, which is what allows you to create database tables.0405

What it does is takes a comma-delimited list of column definitions.0411

You define the columns that you want in your particular table.0417

The command is CREATE TABLE--those are the keywords.0420

And then, you follow it by the name that you want to give the table--for example, you might call it Users.0424

Or for what we are going to be doing in this lesson, we are going to be creating a table called Items to store items' information.0429

And then, you have this comma-delimited list of however many columns you want to create.0435

And what you do is list the name of the column you want to create;0440

you provide the data type of the column; and then you can provide some additional attributes that we are going to talk about0443

to just further define how that column is going to work in the database.0450

And you separate all of the different column definitions by commas.0454

Data types--we talked about that a little in our introduction to databases lesson:0461

SQL provides some data types for data that you store in relational database tables.0463

We are going to specifically talk about some of the specific data types now.0469

There are a couple of numeric data types that we are going to be using.0474

First of all, INT is a data type that represents an integer, just like the int data type in PHP.0478

And what you can do is specify INT, which will allow you to do positive and negative integers.0487

You can also specify as a data type INT UNSIGNED, and that is saying you want an unsigned integer,0491

which means an integer that only holds positive values.0498

We are going to be using that for our item ID's and all of our ID columns in all of our tables.0501

You can also specify a floating-point number using this decimal data type.0507

And what you do is specify the keyword DECIMAL, followed by parentheses, and then followed by two digits.0513

And one we are going to call m, comma, and then the other one, d.0518

What m does is specifies the maximum number of digits that this floating-point number can represent.0523

And then, d is going to represent the number of digits after the decimal point.0528

For example, if we create a column--let's say we create a column (which is what we are going to be doing) called price;0532

and so, we have the name of the column and then data type, and then we specify that we want it to be0541

a maximum of three digits, with two after the decimal place,0548

which means it can only hold numbers of the form x.yz, where it has three total digits, two of which come after the decimal point.0551

We are going to be using that to hold the price of our items in our store.0560

Then, there are a couple of string data types that we are going to be using.0564

The first one is called a CHAR, and it is followed by parentheses with an M parameter.0567

And M is a number that allows you to specify...a CHAR data type says you are creating a fixed-length string;0574

so if you give this data type to a particular column, and you say CHAR(3), what you are saying0585

is that this column that you are using this data type for is going to be a string that is of a fixed length, and it is going to be 3 characters long.0594

An alternative to that is VARCHAR, and what that is: it is a variable-length string that can be up to M characters in length (that you specify).0604

So, you can say VARCHAR(10), which means that this column in this particular table that has this data type0614

can hold a string of variable length, up to 10 characters.0623

There is also the TEXT data type, which is a data type that allows you to store large amounts of string data.0628

And we are going to be using this, for example, for our product description.0637

You might have a product description, maybe, that is a couple of paragraphs long.0639

Well, instead of specifying a VARCHAR to say that this is going to be a variable-length string up to so many digits,0643

you can use something like TEXT, which has a predefined limit to it, but it is very large.0652

And that is, again, for storing large amounts of string data.0656

As mentioned in our CREATE TABLE SQL command, we specify the name of the column, the data type0662

(we just went over the data type), and--there are also some additional attributes you can specify for a particular column.0669

For example, you can specify the attribute called PRIMARY KEY.0675

What that does is: when you specify that in a column's definition, it denotes that that column is the primary key of the table.0679

And when you do this, one thing to note is that if you are defining multiple columns in your table, only one column can have this PRIMARY KEY attribute specified.0685

Another attribute that you can use, which we are going to be using, is called AUTO_INCREMENT.0695

And what that does is: it can be used to apply to integer and floating-point columns--numeric-type columns.0700

And what it does is: when you specify that column as AUTO_INCREMENT, what PHP will do is:0709

when you insert a new row into a table, for whatever column you have specified AUTO_INCREMENT,0716

it is going to look at the largest-value integer or numeric value that is in the table for that particular column,0722

and it is just going to increment it by 1; and it is going to generate that 0728

as the new number for that particular column, for that particular row.0730

For example, let's say we have an item in the store, 1001; these are in a kind of tabular format.0738

It is called item1; maybe it is 15 dollars; well, with AUTO_INCREMENT, when you add a new item to the table,0748

it is going to go ahead and look at the largest item...0756

assuming this was the AUTO_INCREMENT column, so it has this AUTO_INCREMENT specifier specified in the CREATE TABLE command,0759

so this is an AUTO_INCREMENT column, when we add a new item to this table,0767

it is going to look and see, "OK, 1001 was the last item added to the table."0770

When we insert this new item, maybe we will specify that it is called item2 that costs 25 dollars;0775

we are just going to increment this by 1, and now it is going to be given the item ID 1002.0781

Now, what we are going to be doing is going over the command that we are going to use to create our table.0790

We are going to put this CREATE TABLE command into action, and we are going to use it to create a table called Items in our database,0793

which we are going to use to hold the items in our particular store.0801

It is going to contain 5 columns in the table.0805

So you can see here, we have 5 column definitions in this CREATE TABLE statement.0808

And I forgot to mention that actually, after you write CREATE TABLE and the command, and then the name of the table,0813

you have a set of parentheses in which you enclose all of the different column definitions.0819

We have five different columns we are creating.0824

The first one we are going to call itemID, which is going to represent the item ID of our column.0827

We are going to have it be an unsigned integer; that is going to be the data type.0831

We are going to have it be auto-incremented; so that means, every time we add an item to our database, it is going to automatically increment that ID.0836

So, it is going to generate it automatically for us.0843

And then, we are going to note that that is going to be the primary key column of the table.0847

Because item ID's are going to be something that is unique (we can't have two items in our store with the same item ID,0851

because then you wouldn't have a way of identifying them), we are going to use this column as our primary key.0858

Again, a primary key column is a column in which you can only have one row in the table that has a particular value.0862

You can't have multiple rows with the same value.0869

In this case, we are not going to be able to have multiple rows in the table with the same item ID.0872

The next column we are going to create is going to be called name.0878

We are going to give it the data type VARCHAR, so it is going to be a variable-length string;0880

and we are going to allow it to be up to 25 characters in length.0884

We are going to create a price column, and we are going to let it be a floating-point number that can be 7 digits long;0888

and it is going to have two digits after the decimal place.0895

So, we can have a number that looks like this, with 5 digits before the decimal point and two digits after.0898

We are going to use that to hold our price.0906

We are going to have a description column, and we are going to set its data type equal to TEXT.0908

And that is going to allow us to store large amounts of text information about the description for our item.0913

And then, we are going to create an image file extension column.0920

And we are going to use the fixed-length string data type, called CHAR, and we are going to say, "Make it a fixed-length string of length 3."0924

So, that means that we can only enter image file extensions that have length 3,0932

which makes sense, because we will be entering things like jpg, gif, and png, for example,0937

which are file extensions that are three characters in length.0944

One thing to note is that, when you create this table using the CREATE TABLE command,0950

the order in which you list these column definitions within the CREATE TABLE command 0956

is the order in which they are going to be created in the table.0965

For example, the structure of our table is going to look like this: we will have a table called Items,0967

and it is going to have a number of different columns.0976

And essentially, they are going to have an automatic order to them, and the order is going to be this--the way we specified them.0979

And this is going to become important when we start inserting data into our database,0992

because there is a shortcut that you can do for inserting data, where you can just specify the values1000

for all of the different columns, without saying, "I want this to be the item ID and this to be the name."1006

And so, the order that you put them in is going to be dependent on this order in which the columns are defined within the table.1010

Before we go ahead and create that Items table, what we are going to do is:1025

I am going to tell you about two other useful commands.1030

One is called SHOW TABLES, which--after you have selected a database, using the USE command in the MySQL Monitor,1032

you can type SHOW TABLES, and what that is going to do is allow you to list all of the tables that currently exist in that particular database.1039

If we go back to our MySQL Monitor, we are using the advanced_php database that we have just created, so it shouldn't have any tables in it.1047

So, when we type SHOW TABLES, it is going to say 'empty set,' meaning that there are no tables.1053

There is also a DESCRIBE statement that we are going to go over after we create our Items table1062

that allows you to see the structure of a particular table.1067

You type DESCRIBE, and then the name of the table that you want to see the structure of.1069

And we will be running that on Items.1076

Let's go ahead and create that Items table using the CREATE TABLE statement.1080

We are going to say CREATE TABLE--create a table called Items; we are going to have an open parentheses.1087

Our first column is going to be called item ID; it is going to be an unsigned integer (that is going to be the data type).1097

It is going to have the attributes AUTO_INCREMENT and PRIMARY KEY.1106

One thing I forgot to mention is that, when you specify the attributes, you simply separate them by spaces.1111

We are going to say item ID is an unsigned integer that is going to be auto-incremented, and this is going to be the primary key column of the table.1118

We are going to enter a comma, which is going to say, "We are done with this column definition; let's create the next column,1126

which is going to be name," which we decided was going to be a variable-length string of 25 maximum characters.1131

Again, we enter a comma to start a new column definition.1139

We are going to have price, which is going to be a decimal number that can be 7 digits long, with 2 digits after the decimal place.1143

We are going to have a description column of the text data type, which is going to allow us to store a large amount of string data.1152

And then, we are going to create the image file extension--imageFileExt--column.1159

And we are going to have that be a fixed-length string of length 3.1166

And then, what we do is finish all this by having a closing parentheses, and then a semicolon to go ahead and issue the command.1170

And when we hit Enter, it is going to let us know (assuming it was typed correctly) that the query was OK,1179

which means that the command ran successfully and the table should be created.1185

So now, when we type SHOW TABLES, we should see that this table Items has been created.1188

And sure enough, in the advanced_php database, there is a table called Items.1193

Now, if we want to make sure that the structure of the table that we just created is how we want it to be,1199

we can write DESCRIBE Items, followed by a semicolon.1203

And we can see that it outputs a table that has information about that table Items.1207

We can see that it contains an item ID with an unsigned integer as a data type.1212

It is a primary key, and it has this extra attribute called AUTO_INCREMENT.1217

There is a bunch of other information here that we are not going to really get into,1222

but it does provide other information about the table.1225

It has a name column that can be 25 characters in length.1230

It has a price column, a description column, and an image file extension column.1235

And the thing to note is that the order: this table has 5 columns, and they are in the order itemID, name, price, description, imageFileExt.1238

We have another required homework for this lesson, and that is because it is going to help you to set up this Items database1254

that we are going to be using for our web application.1259

What I want you to do is log in to the localhost MySQL server as phpuser, and do that as the Windows Command Prompt, using the MySQL Monitor program.1262

I want you to type the SHOW DATABASES command to see a list of all the current databases that are on the server,1271

to see that we don't have this advanced_php database yet.1277

Then, go ahead and run the CREATE DATABASE command that is going to create our advanced_php database.1280

And then, when you re-run SHOW DATABASES, you should run that to confirm that the advanced_php database has been added to this particular MySQL server.1286

You are going to select that new database for use.1296

So, when we create a table, it is going to create a table in that advanced_php database.1298

So, we are going to do the USE command; we are going to say USE advanced_php.1303

Run the SHOW TABLES command to get a little practice with that, just showing you that there are no tables1309

in this brand-new database that we created (which makes sense, because we haven't added any yet).1312

And then, create an Items table using the CREATE TABLE command that we used in the lecture,1317

that specifies the item ID column, the name, the price, the description, and the image file extension.1323

And you can look at the slides that we have gone over to see the syntax to do that,1327

so that you create the table exactly as we are going to be using it in our web application.1331

After you do that, you should get a 'query OK' message from MySQL, letting you know that the command ran all right.1337

And then, you can go ahead and issue SHOW TABLES again, and verify that now you have an Items table in that advanced_php database.1344

And then, run the DESCRIBE command, specifying Items as the table you want to describe;1350

and verify that all that information you entered in our CREATE TABLE command...the table was successfully created with those attributes;1356

it has those particular columns, and those particular data types, and any particular column attributes we specified.1365

And assuming all those commands worked, it should see the same output that we saw in the lecture today.1371

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.1377

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be learning how we can add data to our database, using the SQL INSERT command.0005

We are going to learn about the syntax of the SQL INSERT command, which is used to add data to a database.0013

We are going to learn about how to specify values that we want to insert into a database.0020

For example, when we insert strings into a database, we have to enclose them in quotation marks.0025

We are going to learn about some rules for doing that.0029

We are going to walk through the process of populating our Items table that we created in our last lesson with the default items we had in our store.0032

In our web application, we have had 6 items that we have had through all of our web application examples that we have had in the store.0044

And we are going to go ahead and add all of those, using INSERT statements.0051

We are going to talk about how you can have a bunch of SQL commands, or SQL statements, in text files.0054

And then, you can just sort of import that text file into the MySQL Monitor, and it will run all of the commands for you.0061

And then, we are going to go over another required homework that is going to have you set up the Items table0069

by populating it with those default six items that we have had in our web store application.0074

As mentioned, the INSERT command is used to insert rows into a table in the database.0082

It has the syntax defined here: it has the two keywords INSERT INTO, followed by the table name.0089

You would say "INSERT INTO Items," for example, and that is going to say that we are going to be inserting data into the Items table.0098

And then, what you do is specify the names of the columns that you are going to be providing data for.0108

You name the different columns: for example, you might say itemID, name, and price.0114

Then, you have the keyword values, and then, within parentheses, you specify the different values0119

that you want to correspond to the different columns you have listed.0125

So, the first value would correspond to whatever column name you could find here.0128

The second would go to this name here, and then so on.0132

And you can do that for as many columns as you need to.0135

There is also a shorter syntax where you can leave out the column names (this section here), 0138

and have a command that would just be INSERT INTO Items, for example.0145

And then, instead of having this column definition, you would just say values.0155

And here, I am just putting them on separate lines (they don't need to be), just for readability.0160

And then, you would just specify the values.0163

Now, the thing to note about that is that (and this was mentioned in the last lesson),0169

when you create a table, and you use the CREATE TABLE command, you specify columns in a particular order.0173

Well, that sets up the structure of that table and how those columns are ordered.0179

So, if you are going to be using this form of the INSERT command without specifying the column names here,0182

and you are just specifying values, you have to specify the values according to how those columns are ordered in the table definition.0190

For columns with numeric data types (for example, our price column), you simply specify0198

the literal value that you wanted to insert into the database without quotation marks.0205

If we wanted to set a price of $15, we would just type 15.00.0210

For columns with string data types, however (for example, a CHAR data type, a VARCHAR, and a TEXT data type),0216

you have to surround them by quotation marks--either single quotes or double quotes.0222

And just as in our PHP strings, if your string that you are inserting into the database contains one of those quote characters itself,0228

you must explicitly escape it, using the escape sequence: backslash, single quote to add a single quote to the string,0237

or backslash, double quote to add a double quote to your string.0244

Another important thing is: for columns that have the AUTO_INCREMENT attribute set0249

(which, for our Items table, is the itemID column, because we want it to generate a new itemID automatically0253

every time we add an item to the table), what you do is: when you provide a value in the INSERT statement for that particular column,0259

if you provided a value of null or you provided a value of 0, then MySQL is going to know 0269

to go ahead and auto-generate, in this case, a new itemID to whatever the next value in the table is.0275

You specify null or 0 to do that.0286

Alternatively, you can also exclusively set the value for an auto-increment column by actually giving it a particular value.0288

You can...for example, if this was our column definition: INSERT INTO, and we had set itemID with the column values...0294

let's say we are just inserting one column; we could explicitly put 1001.0306

And that way, it wouldn't do the AUTO_INCREMENT feature; it would set it to the value explicitly specified.0314

Now, we are going to talk about how to insert items into our database, taking that command that we just learned about abstractly0323

and putting it to work in a real-world example.0329

We are going to be inserting those six default items that we have had in our web store into our database.0333

This command right here is going to be used to insert the first item in the database.0339

We are saying, "Insert into the Items table values for these columns: itemID, name, price, description, and imageFileExt."0345

We are saying, "Give them the values..." in this case, we are explicitly setting this auto-increment column to 1001.0352

And we do that just for this first item.0359

And the reason we are doing that is: AUTO_INCREMENT--the first time you insert an item into a table with it, it automatically starts at 1.0360

If you explicitly set it (in this case, to 1001), then every time we add an additional item, and we specify a null value or a 0 value,0368

as mentioned, then it is going to auto-increment it from the highest item number there in the table.0375

In this case, it will have already been set to 1001; so the second item is going to be added as 1002.0380

We are going to specify the name of the item; notice that it is in quotation marks, because it is a string.0386

We are going to set the price (which is just a number, so there are no quotation marks; it is the string 15).0391

We are going to enter a description (again, because it is a string, it is enclosed in quotation marks),0398

and then the image file extension (in this case, jpg); because it is a string, it needs to be enclosed in single quotation marks.0403

Notice that there are parentheses around the names of the different columns.0411

And then, there are parentheses that surround the different values that we are going to be providing.0417

Let's go ahead and add this first item into our table.0424

We are going to connect to the MySQL database as our phpuser, just as we have done in the past.0430

We are going to use the advanced_php database.0439

And a command that I am going to do...I am going to show the tables that we currently have (we have only created one so far--it is going to be Items).0447

We have an Items table, and I am going to issue a command now that we are going to learn about in the next lesson,0457

called the SELECT command, that lets you see what data is in that particular table.0461

Don't worry about the syntax of this right now.0467

But it is saying, "Give me all of the rows in the Items table."0468

And when we enter it, we can see that it is the empty set; so we know that our Items table is currently empty.0470

Now, we are going to go ahead and insert that first item into the table.0476

We are going to insert into the Items table, and we specify the names of the columns.0479

And then, we specify the values we want to associate with those columns.0503

And after this one, I'll have to go back to the slides; I don't remember exactly what we had.0510

The second one, the name, is a string, so we are going to enclose it in quotation marks.0516

The price was $15; the description (which is another string) is going to be enclosed in quotation marks.0527

This 100% cotton T-shirt is built for comfort.0535

If I continue it on the next line..."for comfort"...I finish the quotation marks; and then, the image file, I believe, was jpg.0548

I'm going to enter jpg, again, in quotation marks.0559

I have the closing parentheses for our list of values, and a semicolon.0563

When we hit Enter, it is going to let us know that the query was OK.0568

If I run this SELECT command (which, again, we are going to learn about in the next lesson) again,0571

to see if we have any data in our Items database, we are going to see this row.0576

We are going to see (it is kind of hard to see here, because of the size of the screen, but basically) that0584

it has the itemID we entered (1001); it has the name (100% Cotton T-Shirt);0589

it has the price ($15); it has "This 100% cotton T-shirt is built for comfort," and then it also has the file extension jpg.0593

Now, the other way that we can insert items in tables, as mentioned, is not by specifying the columns, 0604

but just specifying the values in the order that the columns are defined.0609

And remember, for our auto-increment columns, we can just specify null or 0, 0614

and that is going to have the database automatically generate that for us.0618

We will get to this file in a second, but I have a file that contains INSERT statements for all of the 6 default items that we have.0625

So, I am going to reference it, so that I can type these in manually.0632

We are going to enter the second item into the table; this is a 42" LCD television.0636

We are going to say INSERT (let's see if we can clear a little space here) INTO Items values...0641

And now, I have to specify these values in the way that the table was defined.0661

And let me go ahead and throw an error there to get out of that command.0667

If we describe our Items table using the DESCRIBE command, we can see that the order they were defined in0671

is itemID, name, price, description, and imageFileExt, so that is the way 0678

that I am going to have to specify them in parentheses in our INSERT statement.0682

Now, the first one is itemID; because we want it to auto-increment, we are going to set it to equal the value null.0692

The name is 42" LCD Television; notice that it is in quotation marks.0698

Also, notice, however, that even though this includes a double quote, I don't have to escape it with a backslash,0706

because it is included within single quotation marks; that is similar to how PHP works.0712

I need to make sure that I have the right name for that: 42" LCD Television, $599.99.0717

The next column is price, so we are going to enter, without quotation marks, 599.99.0722

The description: With 42 inches of viewing screen, you feel like you are a part of the movie.0729

And then, the image file extension; in this case, it is a GIF, so we enter gif in quotation marks.0755

We finish it with a closing parentheses, add a semicolon, and hit Enter.0765

And it is going to let us know that the query was OK.0771

It is going to say "one row is affected," which I didn't mention before, which shows that one row was inserted.0773

Now, if we run our SELECT query again to see what is in the Items table (let's see if there is some way I can get this so it looks better),0777

we can see that it has added two items to the table.0790

I am going to do a modified SELECT statement, which you will learn more about in the next lesson.0793

I am just going to get rid of the description; I am not going to have it pull up the description value0796

in the results that it returns, just so we can see it all in one screen.0803

And again, don't worry about the syntax of this right now.0808

You can see that it has added another row to the table.0818

It gave it the itemID value 1002, so you can see that, when we specified null for itemID, it went ahead and auto-incremented it.0821

It took the greatest value that was in that column in the table (which was 1001) and incremented it by 1.0828

And then, we can see that it went ahead and set all of the different columns for the table.0833

It set the name to 42" Television, price to 599.99, and the image file equal to gif.0836

One of the things that you can do is: the MySQL Monitor client can be used to run multiple commands at the same time.0845

And what it allows you to do is: you can create a text file that contains all of these commands that we have been typing into this interactive MySQL prompt.0851

You can go ahead and edit them offline in a text file, and then import this text file into the MySQL Monitor.0859

It will go ahead and run all of the commands in that particular file.0867

And the common thing that that is used for is INSERT statements.0872

For example, if we want to insert a bunch of data into our database, here I have this text file created.0875

And as you can see, it contains a bunch of INSERT statements, all with syntax exactly as you would use if we typed it in the command prompt.0881

And it just contains a bunch of INSERT statements that insert all of our 6 default items into the database.0888

You can contain any SQL statements you want in these text files.0895

For example, one of the statements that I have at the top is to use advanced_php,0899

because that is going to let MySQL know that we are inserting these items into the Items table that is in the advanced_php database.0903

That is something that you can include.0911

The way that you have the MySQL Monitor run these commands is: you use the MySQL command;0916

but then, what you do is use a less than sign, and then the name of the file that contains all the commands you want to run.0923

Now, the commands can be held in any text file with any extension, as long as it is a text file.0930

But the convention is to end files in this .sql extension, and that is what we are going to use in this course.0935

This is saying, "I want to connect to the MySQL database on the localhost (because no host is specified) as a phpuser."0943

"I want to be prompted for the password."0951

And then, one other thing to notice here is: let's say we hadn't included that USE advanced_php statement0955

in our SQL file that I was just talking about; we can specify what database we are going to use at this MySQL command prompt,0961

by...the last thing we enter before the less than sign is the name of the database we want to use.0969

This is going to say, "Connect to the localhost MySQL database as phpuser; prompt me for the password."0974

"When I log in, I want to be using the advanced_php database, so I don't have to type the USE command."0981

"And then, I want you to run these commands contained in commands.sql."0988

Now, one thing to note is that, when you specify, after this less than sign, the name of the file0994

that contains the SQL commands that you want to run, you have to make sure that the MySQL Monitor knows where to find that file.1000

If an absolute path is not specified, it interprets it as a relative path;1014

so in this case, commands.sql would have to be in the same directory where this MySQL command is being run from.1017

So, you might have to, for example, specify an absolute path.1023

Maybe you have an SQL file called items.sql stored in the user1 directory of the Users directory on the C: drive.1031

So, you would replace this commands.sql after the less than sign with an absolute path to the file.1042

That way, that is one problem that you might encounter.1047

You need to make sure that MySQL is able to find the SQL file that you are trying to import.1049

We already know that this file was set up to insert the 6 default items into the database.1057

But we have already inserted the first two, so I am going to go ahead and delete this from this file.1067

And then, I am going to have it insert into the file the remaining four items.1073

As you can see here, what I have done is: the next two items--I have just specified the values.1078

And so, I have to specify the values in the order that the table was set up in.1084

It's itemID, followed by the name, followed by the price, description, and image file extension.1090

Then, in this last part, in the fourth and fifth one, we are going to explicitly name the columns.1096

I'll put this on a separate line.1102

We are saying the first value we are providing is the itemID; we are providing it the name, price, description, and image file extension.1104

Here, this should be null.1112

And then, one thing to note is that, if you are explicitly specifying the columns of the values that you are supplying,1116

you can actually put them in any order you want.1126

You just have to switch the order of the way you are listed in the values parentheses.1128

For example, we want to specify price first and then name; we would switch the order here, and then subsequently switch the order in the list down here.1132

What this statement is going to do is say, "Insert into Items itemID, price, name, description, and imageFileExt."1143

So, this one is going to be interpreted as itemID; this will be interpreted as price; this will be interpreted as name.1148

So, it will still work; and it just allows you to switch the order around.1153

And that is just to give you an example of the different flavors you can use for the INSERT statement.1156

Let's see this file...I'll get the address of this file.1169

I'm going to exit altogether and get a fresh command prompt.1180

I'll change to our mysql/bin directory, so we get access to that MySQL program.1191

We are going to connect to the localhost; we are going to connect to phpuser.1200

We are going to be requested for the password; we are not going to specify that we want to use the advanced_php...1205

Actually, let's go ahead and do that; let's specify that we want to use the advanced_php database.1211

And then, in our items.sql file, I am going to eliminate this line.1216

When we import this file, it is going to know that we are using that advanced_php database already.1220

And then, I'm going to specify, using the less than sign, the SQL file that I have called items.sql1227

that contains these INSERT statements for the remaining four items that we are inserting into the database.1235

And I am going to specify the absolute path to it, which is in this particular directory that I just copied from the Windows Explorer.1240

It is called items.sql.1255

And when I hit Enter, it is going to ask me for the password.1257

And then, assuming everything runs fine, it is going to run things and then return the command prompt back to the way it was before.1264

So now, to make sure that they were all added properly, I'm going to log back in as phpuser to the advanced_php database.1270

And now, let me type SELECT; again, I am not going to bring up a description, because it makes things longer.1293

Again, typically keywords (they don't have to be capitalized, but) like SELECT in this particular case, by convention, are capitalized.1309

This is going to say, "Give me all of the information about all of the items in our Items table."1315

And we can see that it was able to successfully add those other four items.1320

It added 1003, 1004, 1005, 1006, with the values that we specified.1323

We saw that you can use either the format we used to explicitly specify the column names,1329

or you can just explicitly specify the values in the order in which the columns are defined in the table.1335

Or, you can explicitly specify the columns in any order that you want, as long as the values that you supply match up to those particular columns.1340

The required homework is to get you to populate the Items table you created in the last required homework1353

with the 6 default items we have been using in our store.1359

And what you should do is log into MySQL as phpuser, using the MySQL command prompt.1363

And I'll have you experiment with a couple of different things that we did here in the lecture,1369

so you get experience with both manually typing commands, and then also using that less than sign1373

to import commands to be run by MySQL.1379

After you log in, select the advanced_php database for use (which you use the USE command to do).1384

And then, run an INSERT command that is going to insert item 1001 into the database.1390

And in this case, we are going to have you explicitly set the itemID column to 1001.1396

And what that is going to do is seed that AUTO_INCREMENT column, so that any item added after that--1401

when we specify null for itemID, it is going to add 1 to that.1406

So, the next item will be 1002, then 1003, and so forth.1409

And you can get the information to add for these particular items (the name, the price, the image file extension, the description)1413

from, for example, items.txt, which is the database file we have been using to store information about all of our items in our store.1421

That has been our database to figure out what values you need to put for each item when you enter them into the database.1428

Then, run the SELECT * FROM Items command to verify that the item was successfully added.1436

And then, exit the MySQL Monitor client.1442

Then, what I am going to have you do is create a file called items.sql in whatever directory you want1445

that is going to contain INSERT commands for each of the remaining 5 items in the store.1450

One of them you are going to answer manually; the others, you are going to use an SQL file for.1455

And I want you, for the first three items that you add, to use the INSERT syntax that includes the column name.1461

You are going to explicitly specify the column names (itemID, name, price, and so forth).1468

And then, for the last two, use the INSERT syntax that just provides the values.1473

It just has values with the parentheses containing the values you want.1477

Just remember that you have to specify those values in the order in which the columns are defined for that particular table.1483

Then, use that less than operator to input this SQL file into MySQL Monitor to run these INSERT commands.1489

And make sure that you specify the correct absolute path (or relative path, if you want--if you understand how to do that)1498

to this items.sql file that you have created, which is the name of the file that is going to contain all of these INSERT statements.1505

And so, you need to make sure to specify that it knows where to find that.1513

You can optionally, in your items.sql file, include USE advanced_php as the first line of the file1518

to make sure that these statements get evaluated on the advanced_php database,1528

because if they don't, you will get an error from MySQL.1532

Or, you could use it using the MySQL command prompt, and specifying user, p, and then specifying the name of the database,1536

in which case (and a less than, in the name of your file) you can leave this statement out here.1546

I'll let you decide whatever you want to do for that.1552

Then, log into the server as phpuser; run this SELECT * FROM Items again (which is saying,1554

"Give me all the information about all the rows in the Items table) to verify1559

that all those items that you had in your SQL file were successfully added.1563

A couple things to note: make sure that you properly enclose all of the strings in quotes.1570

All of those string data fields, we have to enclose in quotes.1575

And escape any quote characters, as needed.1578

And you will notice that, on the descriptions that we currently have for some of the items in the store,1581

there are single quotes contained within them; and so, you are going to need to escape those with backslash, single quote.1585

The alternative would be that, as in PHP strings, you could enclose the string in double quotes.1594

And therefore, for example, if you have the word you'll with the apostrophe, you don't have to escape that single quote.1600

I'll leave that up to you.1613

And then also, just make sure that mysql.exe, the MySQL Monitor, can find your MySQL file.1614

So, you are going to have to specify a correct path to that file after the less than sign after the MySQL command.1619

That ends today's lesson; thank you for watching Educator.com; I look forward to seeing you next time.1626

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to learn how to retrieve data from our database using the SQL SELECT command.0005

We are going to go over the syntax of the SELECT command, and then we are going to talk about two different clauses that you can add,0011

which are additions you can add to the SELECT command.0018

The WHERE clause will allow you to restrict what rows from a table you want to retrieve.0023

And the ORDER BY clause is going to allow us to specify, when we retrieve rows from a table using the SELECT command, how we want the results ordered.0031

The SELECT command (or query, as it is often called) is used to retrieve rows from a database that match specified criteria that we choose.0044

Now, it is sometimes called a SELECT command, sometimes called a SELECT statement, sometimes called a SELECT query or just a query.0056

I will use those terms interchangeably; mostly, I will be using the term 'query.'0062

So, if I say, "We are executing a query on the database," that is going to be saying 0065

that we are executing a SELECT command on the database, which is going to retrieve data from the database.0070

What the syntax of the SELECT command is: you have the SELECT keyword, and then you specify the names of the columns0077

that you want to retrieve data for, separated by commas.0086

We are saying, "Give me the values for column 1 and column 2" and then the FROM keyword--"from table name" and then you specify the table name.0091

So, this would say, "Give me all the values for column 1 and all the values for column 2 from the table named by Table Name."0101

And what happens is: the SELECT query returns its results in a tabular format ordered by how the columns are listed in the query.0113

For example, if we ran this query, we would get what is called a result set.0125

It is a table of data, and it would have two columns in it, because we specified two columns that we want to retrieve data for.0131

And then, it would have the values of each row in the table Table Name.0147

So, if we have a table called (in this case) Table Name, this query would retrieve the values0155

for the column1 name column and the column2 name column for every row in Table Name table.0162

And it would list them in a tabular format.0169

The order in which these columns are going to appear is the order in which we specify them here.0171

If we would switch it around, then these would be reversed in the result set.0174

And again, the term result set is used to refer to the table of data that is returned when you execute a SELECT query.0179

If you want to retrieve all of the columns from the table (which is something you often want to do),0188

you can use the wildcard in place of the list of column names.0192

So, we could type a query (and this is something that we talked about in the homework example for the last lesson,0196

and when inserting items, we used the database to verify that they were inserted, which we didn't go over).0201

But we said SELECT * from Items, and what that is saying is, "Give me all of the values for all of the columns for all of t