Web technologies and e-services: Lecture 5.2. This lesson provides students with content about: object oriented programming in PHP; accessing properties and methods; constructors and destructors; PHP sessions; PHP and MySQL; MySQL queries inside of PHP;... Please take a close look at the course content!
ADVANCED PHP Content Contents • Class • Sessions • PHP and MySQL Class Object oriented programming in PHP • PHP, like most modern programming languages (C++, Java, JavaScript, etc.), supports the creation of objects • Creating an object requires you to first define an object class (containing variables and/or function definitions) and then using the “new” keyword to create an instance of the object class (Note that the object must be defined before you instantiate it.) Defining (declaring) a class • Use the “class” keyword which includes the class name (case-insensitive, but otherwise following the rules for PHP identifiers) Note: The name “stdClass” is reserved for use by the PHP interpreter Accessing properties and methods • Once you have an object, you access methods and properties (variables) of the object using the -> notation Constructors and destructors • Constructors are methods that are (generally) used to initialize the object’s properties with values as the object is created Declare a constructor function in an object by writing a function with the name construct() { • Destructors (defined with a function name of destructor() ) are called when an object is destroyed Inheritance • Use the “extends” keyword in the class definition to define a new class that inherits from another of parent object More on session variables • You need to include a call to the session_start() function for each page on which you want to access the session variables • A session will end once you quit the browser (unless you’ve set appropriate cookies that will persist), or you can call the session_destroy() function • The function session_unset() removes all session variables If you want to remove one variable, use the unset($var) function call • The default timeout for session files is 24 minutes It’s possible to change this timeout Deleting all session variables Session example 3 } view the output page PHP and MySQL 19 Putting Content into Your Database with PHP • Connect to the database server and login (this is the PHP command to so) mysql_connect("host","username","password"); • Choose the database mysql_select_db("database"); • Host: mysql Database: martin Username: martin Password: Send SQL queries to the server to add, delete, and modify data mysql_query("query"); (use the exact same query string as you would normally use in SQL, without the trailing semi-colon) • Close the connection to the database server (to ensure the information is stored properly) mysql_close(); Student Database: data_in.php Putting Data in the DB