Php and Mysql Slides

March 15, 2018 | Author: paraagpandey | Category: Php, Hypertext Transfer Protocol, My Sql, Databases, Web Server


Comments



Description

PHP & MySQL by ExamplesSimone Grassi PhD at Trinity College Dublin Research on Software Architectures Distributed Systems Group [email protected] PHP Advantages Multiplatform Supports most important Databases Wide set of included functions Many Open Source resources (es: PEAR http:// pear.php.net) Included in many Linux distributions 40% of Internet Domains uses PHP Wide International Community (in 2 clicks from google you find the solution for 99% of problems) PHP is a scripting language PHP has an HTML-centric approach making easy and fast to develop scripts for the web. <!-- example_1.php --> <html><header><title>PHP Example</title></header> <body><h1>My Example</h1> <form action="example_1.php" method="POST"> FirstName: <input type="text" name="firstname"><br/> LastName: <input type="text" name="lastname"><br/> Born (yyyy - mm - dd) : <input type="text" name="year" size="4"> <input type="text" name="month" size="2"> <input type="text" name="day" size="2"><br/> </form> <?php if ($_POST['firstname']) { $weekday = date('l',mktime(0,0,0,$month,$day,$year)); print "Hi $firstname $lastname, you were born on $weekday"; } ?> </body></html> PHP is Server Side (I) The client doesn't care about PHP, just receive an HTML/JS (or XHTML/CSS/JS) page. The web server work in touch with PHP (usually like a module) and let PHP do the interpretation of the script. The result of the interpretation is sent back to the browser. BENEFITS - Concentrate complexity in the server - Configure only the server to communicate with a third party database (like MySQL) DRAWBACKS - The server must execute all requests - Saving the output pages from the client does not allow to create a real copy of the web site <!-- hello_world.php --> <html> <head> <title>Test Page</title> </head> Hello World! </body> </html> Client Browser 5) Reply 1) Request (hello_world.php) Apache PHP 2) Read <!-- hello_world.php --> <html> <head> <title>Test Page</title> 3) Interpretation </head> <? echo ‘Hello World!’; ?> </body> </html> 4) Collect output PHP is Server Side (II) - Only the PHP output becomes a browser page - Everything outside <? ?> tags is simply “forwarded” to the output Client Browser 5) Reply 1) Request (helloWorld.php) Apache PHP 2) Read 4) Collect output <!-- no_output.php --> <html> <head> <title>Test Page</title> </head> </body> </html> <!-- no_output.php --> <html> <head> <title>Test Page</title> </head> <? if ($a == 10) $b = $a; else $b = $a * 10; ?> </body> </html> 3) Interpretation Learning PHP ✔ Basic syntax (similar to c, perl) ✔ Types and Variables ✔ Array, Hash ✔ String manipulation ✔ File management ✔ Expressions, Operators ✔ Control Structure ✔ Functions ✔ Function Reference ✔ Classes and Objects http://www.php.net/manual/en/ PHP Variables (I) - The char $ (dollar) is used to specify a variable like: $my_variable, $_anther_variable. - No number as first char, $1_name is not allowed. PHP is loosly typed, the interpreter make on the flight decision about variable type. If you add two values, PHP tries to cast them to int and then do the add operation: <? // variables_1.php $add = '1' + 1; echo $add.'<br/>'; // outputs ‘2’ $add = 1 + 'test'; echo $add.'<br/>'; // outputs ‘1’ $add = 'long'+' '+'composed string'; echo $add.'<br/>'; // outputs ‘’ $add = 'long'.' '.'composed string'; echo $add.'<br/>'; // outputs ‘long composed string’ echo '$add'.'<br/>'; // outputs ‘$add’ echo "this is my string: $add"; // outputs ‘this is my string: long composed string’ ?> PHP Variables (II) Function isset tests if a variable is assigned or not: $A = 1; if (isset($A)) print “A isset”; if (!isset($B)) print “B is NOT set”; Using $$: $help = “hiddenVar”; $$help = “hidden Value”; echo $$help; // prints hidden Value $$help = 10; Is like: $hiddenVar = “hidden Value”; $help = $$help * $$help; echo $help; // print 100 A string is a sequence of chars: $stringTest = "this is a sequence of chars"; for ($i=0;$i<strlen($stringTest);$i++) { $char_i = $stringTest[$i]; print $char_i; } echo $stringTest; A single quoted strings is displayed “as-is”: Strings (I) $age = 37; $stringTest = 'I am $age years old'; // output: I am $age years old $stringTest = “I am $age years old”; // output: I am 37 years old Concatenation: $conc = ”is “.”a “.”composed “.”string”; echo $conc; // output: is a composed string $newConc = 'Also $conc '.$conc; echo $newConc; // output: Also $conc is a composed string Explode function: $sequence = “A,B,C,D,E,F,G”; Strings (II) $elements = explode (“,”,$sequence); // Now elements is an array with all substrings between “,” char print_r($elements); var_dump($elements); The output is: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G ) Arrays (I) Groups a set of variables, every element stored into an array as an associated key (index to retrieve the element) $books = array( 0=>”php manual”,1=>”perl manual”,2=>”C manual”); $books = array( 0=>”php manual”,”perl manual”,”C manual”); $books = array (“php manual”,”perl manual”,”C manual”); echo $books[2]; // output: C manual Arrays with PHP are associative $books = array( “php manual”=>1,”perl manual”=>1,”C manual”=>1); // HASH echo $books[“perl manual”]; // output: 1 $books[“lisp manual”] = 1; // Add a new element Arrays (II) $books = array( ”php manual”,”perl manual”,”C manual”); // Common loop for ($i=0; $i < count($books); $i++) print ($i+1).”-st book of my library: $books[$i]”; each: $books = array( “php manual”=>1,”perl manual”=>2,”C manual”=>3); while ($item = each( $books )) // Retrieve items one by one print $item[“value”].”-st book of my library: ”.$item[“key”]; // each retrieve an array of two elements with key and value of current element each and list: while ( list($value,$key) = each( $books )) print “$value-st book of my library: $key”; // list collect the two element retrieved by each and store them in two different // variables Arrays (III) Multidimensional arrays $books = array( array(“title”=>“php manual”,”editor”=>”X”,”author”=>”A”), array(“title”=>“perl manual”,”editor”=>”Y”,”author”=>”B”), array(“title=>“C manual”,”editor”=>”Z”,author=>”C”)); Common loop for ($i=0; $i < count($books); $i++ ) print “$i-st book, title: ”.$books[$i][“title”]. ” author: “.$books[$i][“author”].“ editor: “.$books[$i][“editor”]; Use list and each for ($i=0; $i < count($books); $i++) { print “$i-st book is: “; while ( list($key,$value) = each( $books[$i] )) print “$key: $value ”; print “<br/>”; // or “\n” } Functions (I) The syntax to implement a user-defined function is : function function_name([parameters-list]opt) {……implementation code……} - parameters-list: sequence of variables separated by “,” - function names aren’t case-sensitive; - to each parameter can be assigned a default value; function function_name($param1,$param2=1,$param3=“string1”); - arguments can be passed by value or by reference It’s possible using a variable number of parameters Parameters by reference and by value: <? function test_function(&$by_reference,$by_value) { $by_reference += 10; $by_value += 10; return ‘any value’; } $by_ref = 10; $by_value = 10; $returned_string = test_function($by_ref,$by_value); print “by_ref: $by_ref by_value: $by_value”; print “returned value: $returned_string”; // output by_ref: 20 by_value: 10 ?> Functions (II) PHP Editors and Development Suites COMMERCIAL SOLUTIONS: - Zend Studio (www.zend.com) - NuSphere PHPEd (www.phped.com) NON-COMMERCIAL SOLUTIONS: - PHPEdit (www.phpedit.net) - Davor's PHP Editor () Search for editors and IDEs: - http://www.thelinuxconsultancy.co.uk/phpeditors/ PHP & Mysql - PHP 4 support directly MySQL, including libraries with functions to connect and send receive data with a MySQL server. Compiling PHP is enough to request the mysql support #./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql - PHP 5 can be compiled with MySQL support but mysql libraries are no longer included in PHP distribution. Compiling PHP must specify the location of mysql libraries #./configure --with-apxs2=/usr/local/apache2/bin/apxs \ --with-mysql=/usr/local/mysql - Using support in Linux distribution or rpm packages all can be installed in a single command PHP Mysql functions (I) PHP compiled with MySQL support includes a complete set of functions to access mysql databases: mysql_affected_rows -- Get number of affected rows in previous MySQL operation mysql_change_user -- Change logged in user of the active connection mysql_client_encoding -- Returns the name of the character set mysql_close -- Close MySQL connection mysql_connect -- Open a connection to a MySQL Server mysql_create_db -- Create a MySQL database mysql_data_seek -- Move internal result pointer mysql_db_name -- Get result data mysql_db_query -- Send a MySQL query mysql_drop_db -- Drop (delete) a MySQL database mysql_errno -- Returns the numerical value of the error message from previous MySQL operation mysql_error -- Returns the text of the error message from previous MySQL operation mysql_escape_string -- Escapes a string for use in a mysql_query. mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both. mysql_fetch_assoc -- Fetch a result row as an associative array mysql_fetch_field -- Get column information from a result and return as an object mysql_fetch_lengths -- Get the length of each output in a result mysql_fetch_object -- Fetch a result row as an object mysql_fetch_row -- Get a result row as an enumerated array mysql_field_flags -- Get the flags associated with the specified field in a result ... ... mysql_field_len -- Returns the length of the specified field mysql_field_name -- Get the name of the specified field in a result mysql_field_seek -- Set result pointer to a specified field offset mysql_field_table -- Get name of the table the specified field is in mysql_field_type -- Get the type of the specified field in a result mysql_free_result -- Free result memory mysql_get_client_info -- Get MySQL client info mysql_get_host_info -- Get MySQL host info mysql_get_proto_info -- Get MySQL protocol info mysql_get_server_info -- Get MySQL server info mysql_info -- Get information about the most recent query mysql_insert_id -- Get the ID generated from the previous INSERT operation mysql_list_dbs -- List databases available on a MySQL server mysql_list_fields -- List MySQL table fields mysql_list_processes -- List MySQL processes mysql_list_tables -- List tables in a MySQL database mysql_num_fields -- Get number of fields in result mysql_num_rows -- Get number of rows in result mysql_pconnect -- Open a persistent connection to a MySQL server mysql_ping -- Ping a server connection or reconnect if there is no connection mysql_query -- Send a MySQL query mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection. mysql_result -- Get result data mysql_select_db -- Select a MySQL database mysql_stat -- Get current system status mysql_tablename -- Get table name of field mysql_thread_id -- Return the current thread ID mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the result rows PHP Mysql functions (II) Networking details Depending of the project a good networking design is needed to have good benchmarks. Different scenarios are possible: - A single server Hosting Web Server (with PHP) and MySQL - One host for Web Server (with PHP) and a second host for MySQL - You must check the transfer rate and the speed of the connection - You must grant enough permission to access MySQL from PHP but taking care of security issue - You need to encrypt data if the path from the Web Server to MySQL is not completely in a trusted environment - Many Server with MySQL - One server must be the primary, the others are slave - Every Web Server will do read-only queries into the nearest MySQL server - Every slave server must be properly configured to replicate the Master Server databases - Every modification to the database must be done to the Master Server Database requirements MySQL in always under strong development. Planning your application you need to find out if the last stable version has all the functionalities you need from the database. - Foreign keys (from 3.23.44 with InnoDB tables) Allows to automatically check for referential integrity executing specific tasks after the modification of foreign keys - Transactions (3.23 Max and all >4.0 with InnoDB tables) Allows to execute a set of tasks like an unique atomic action - Hidden queries (4.1) Allows to retrieve data with more complex queries on more than one level - Triggers, Views, Stored Procedures, etc... (5.0 now stable) Create the database #mysq –u root –p Enter password:#### mysql>create database weben_2005 mysql>use weben_2005 mysql>CREATE TABLE personnel ( >fistname varchar(25), >lastname varchar(20), >nick varchar(12), >salary int); mysql>INSERT INTO personnel VALUES (’Marc’,’Maverick’,’Mav’,’20000’); mysql>INSERT INTO personnel VALUES (’John’,’Vinny’,’Jo’,’35000’); Let’s suppose PHP and MySQL are installed and working. Now we can create the working db, one possibility is from the console (or from phpMyAdmin) phpMyAdmin http://www.phpmyadmin.net/home_page/ Easy to install, is a PHP application used like an intranet tool. Un compress the tar.bz2 file into your document root: #tar jxvf phpMyAdmin-2.6.4-pl3.tar.bz2 Rename the directory: #mv phpMyAdmin-2.6.4-pl3 phpmyadmin Then edit phpmyadmin/config.inc.php to match your MySQL parameters (server address, user, password etc...) Then access your MySQL databases using a browser. If you don’t have virtual domains the address is: http://localhost/phpmyadmin/index.php View the database from a PHP script <html> <?php // view_table.php $db = mysql_connect(“localhost”,”guest”,””); if (!mysql_select_db('weben_2005',$db)) die('Error selecting Database!'); $result = mysql_query(“SELECT * FROM personnel”,$db); echo “<table>”; echo “<tr><td><b>Full Name</b></td><td><b>Nick Name</b></td> <td><B>Salary</b></td></tr>”; while ($myrow = mysql_fetch_array($result)) { echo “<tr><td>”; echo $myrow[“firstname”]; echo “ “; echo $myrow[“lastname”]; echo “</td><td>”; echo $myrow[“nick”]; echo “</td><td>”; echo $myrow[“salary”]; echo “</td></tr>”; } echo “</table>”; ?> <br/><a href=’add_table.php’>Insert New Element</a></html> view_table.php The output Full Name Mark Maveric John Vinny Nick Name Mav Jo Salary 20000 35000 <html> <table> <tr> <td><b>Full Name</b></td> <td><b>Nick Name</b></td> <td><B>Salary</b></td> </tr> <tr> <td>Mark Maverick</td> <td>Mav<td>20000<tr><td>John Vinny</td> <td>Jo</td> <td>35000</td> </tr> </table> </html> mysql_connect() try to create the connection to a MySQL database server. Let’s see the online php reference (www.php.net) $db = mysql_connect(“localhost”,”guest”,””); Database connection Select the correct DB After the correct connection to the DB, mysql_select_db() allows to select the requested DB. mysql_select_db('weben_2005',$db) Line 5: mysql_query() sends a SELECT to the database to retrieve data $result = mysql_query(“SELECT * FROM personnel”,$db); Query the database Retrieve data Line 9: mysql_fetch_array() sends a SELECT to the database to retrieve data while ($myrow = mysql_fetch_array($result)) {} view_table.php output Adding new Records to DB We sow how to view records, now let’s add new records. First we’ll create a static form <html> <body> <form method=“post” action=“datain.php”> First name:<input type=“Text” name=“first”><br> Last name:<input type=“Text” name=“last”><br> Nick Name:<input type=“Text” name=“nickname”><br> Salary:<input type=“Text” name=“salary”><br> <input type=“Submit” name=“submit” value=“Enter Information> </form> </html> Insert data Just compile all fields, then submit data pressing “Enter Information” button Now we have a form that will post the information to a page “datain.php”. We must code this page so that it is able to process the posted data and send it to our MySQL database. <html> <?php Collect and save data (datain.php) $db = mysql_connect("localhost","guest",”mypwd"); mysql_select_db("learndb",$db); $sql = "INSERT INTO personnel (firstname,lastname,nick,salary) VALUES(‘”.$_POST[“first”].”',‘”.$_POST[“last”].”',‘”. $_POST[“nickname”].”',‘”.$_POST[“salary”].')"; if ($result = mysql_query($sql)) echo “Thank you!Entry correctly added.<br/>”; else echo “Error executing query ‘$sql’<br/>”; ?> <br/><a href='view_table.php'>View Table</a> </html> datain.php output After the submit, the destination script is executed, the output message just display that everything has been saved view data again Now we just verify the correct execution of INSERT statement POST and GET Variables sent to Apache using a POST form are accessible by PHP code using the array $_POST <form method=“post” action=“datain.php”> First name:<input type=“Text” name=“first”><br> Last name:<input type=“Text” name=“last”><br> Get variables are accessed by PHP using $_GET array http://domain/myscript.php?var1=string1&var2=string2&var3=string3 $_GET[‘var1’] = string1; $_GET[‘var2’] = string2; $_GET[‘var3’] = string3; Easy to install, is a PHP application used like an intranet tool. Un compress the tar.bz2 file into your document root: viewdb2.php 1: <html> 2: <?php // viewdb2.php 3: $db = mysql_connect("localhost","root","mypwd"); 4: mysql_select_db("learndb",$db); 5: $result = mysql_query("SELECT * FROM personnel",$db); 6: echo "<table border=2>"; 7: echo "<tr><td><b>Full Name</b></td><td><b>Nick Name</b></ td><td><b>Options</b></td></tr>"; 8: while ($myrow = mysql_fetch_array($result)) { 9: echo "<tr><td>".$myrow["firstname"]." ".$mysql["lastname"]."</td><td>".$myrow["nick"]; 10: echo "</td><td><a href=\"view.php?id=".$myrow[id]."\">View</a></td></tr>"; 11: } 12: echo "</table>"; 13: ?> 14: <br/><a href='add_table.php'>Insert New Element</a></html> Adding a unique ID (I) Using phpMyAdmin we add a new unique int ID: - from table structure select add new field at the beginning of the table - insert the name “id” just a common way to call the id, other stadard is: personnel_id - select type INT, specify Unsigned We just need a positiv integer - Specify PRIMARY KEY I means it will be a Unique identifier for every record - Specify Auto_increment When a new record is inserted MySQL automatically assign to id the last id+1 - Then Click SAVE Adding a new ID (II) Now let us see the difference using the Table Dump, follows the structure and all records: CREATE TABLE `personnel` ( `id` int(10) unsigned NOT NULL auto_increment, `firstname` varchar(60) NOT NULL, `lastname` varchar(100) NOT NULL, `nick` varchar(20) NOT NULL, `salary` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; --- Dumping data for table `personnel` -INSERT INTO `personnel` VALUES (1, 'Mark', 'Maveric', 'Mav', 20000); INSERT INTO `personnel` VALUES (2, 'John', 'Vinny', 'Jo', 35000); INSERT INTO `personnel` VALUES (3, 'Simone', 'Grassi', 'simo', 15000); viewdb2.php This is the output. Some data is displayed in the table, then an Option row is added to reach more informations http://localhost/weben_2005/examples/view.php?id=1 View a single record: view.php View accept the id to retrieve (GET). Retrieve data about this Entry, then display values to the browser. 1: <html> 2: <?php // view.php 3: $db = mysql_connect("localhost","guest","mypwd"); 4: mysql_select_db("learndb",$db); 5: $result = mysql_query("SELECT * FROM personnel WHERE id=".$_POST["id"],$db); 7: $myrow = mysql_fetch_array($result); 8: echo "First Name: ".$myrow["fistname"]; 9: echo "<br>Last Name: ".$myrow["lastname"]; 10: echo "<br>Nick: ".$myrow["nick"]; 11: echo "<br>Salary: ".$myrow["salary"]; 12: ?> 13: <br/><a href='viewdb2.php'>Go Back to Table</a></html> View.php output Mysql_fetch_array cannot retrieve data, $result is not a valid MySQL result resource Find the mistake We know that there is an error retrieving data, in line 6. But usually must take care of: Line 2: Check if the connection is correct Line 3: Check if the db is correctly selected Line 5: Check if the query is correctly executed Line 6: Check if data is retrieved 1: <html> 2: <?php // view.php query string was ok but the result was empty 3: $db = mysql_connect("localhost","guest","mypwd"); 4: mysql_select_db("learndb",$db); 5: $result = mysql_query("SELECT * FROM personnel WHERE id=".$_GET["id"],$db); // Was POST, but we receive data by GET 7: $myrow = mysql_fetch_array($result); 8: echo "First Name: ".$myrow["fistname"]; 9: echo "<br>Last Name: ".$myrow["lastname"]; 10: echo "<br>Email address: ".$myrow["email"]; 11: echo "<br>Salary: ".$myrow["salary"]; 12: ?> 13: </html> Correct output The query is correct and the relative output Separating HTML & PHP FIRST STEP: PRINTING HTML FROM PHP - As PHP Novice in year 2000 I started my first PHP script. It was amazing how easy was to create dynamic HTML pages - After a while it’s easy to understand how crazy and complicated could become a file with PHP and HTML tags SECOND STEP: USING TEMPLATES TO SEPARATE PHP FROM HTML <?php ?> html+php Template engine* html * Smarty is a known and widely used template engine <?php include('Smarty.class.php'); // create object $smarty = new Smarty; // assign some content. This would typically come from // a database or other source, but we'll use static // values for the purpose of this example. $smarty->assign('name', 'george smith'); $smarty->assign('address', '45th & Harris'); // display it $smarty->display('smarty.tpl'); ?> Smarty crash course TEMPLATE BEFORE (smarty.tpl) <html> <head> <title>User Info</title> </head> <body> User Information:<p> Name: {$name}<br> Address: {$address}<br> </body> </html> TEMPLATE AFTER (output HTML) <html> <head> <title>User Info</title> </head> <body> User Information:<p> Name: george smith<br> Address: 45th & Harris<br> </body> </html> Smarty crash course (II) line line line line line 2: Smarty must be included to be used 4: Instantiate Smarty object to be able to use methods/functions 8: assign API tells Smarty to substitute a tag with a string 9: a second assignment for the second variable 11: finally another API is called to render the template and obtain the output string. 1:<?php 2:include('Smarty.class.php'); 3:// create object 4:$smarty = new Smarty; 5:// assign some content. This would typically come from 6:// a database or other source, but we'll use static 7:// values for the purpose of this example. 8:$smarty->assign('name', 'george smith'); 9:$smarty->assign('address', '45th & Harris'); 10:// display it 11:$smarty->display('smarty.tpl'); 12:?> Smarty crash course (III) What we obtained? - Graphical User Interface (HTML) is separated from code - All files can be collected into a specific directory - Team work can be better separated. Professionals about graphics just care about graphical requests, then from the created template is created the template file for the specific template engine (like smarty) - Not only the content is dynamic but also some graphical adjustments - The business logic can be changed without care about how the output is displayed (not always 100% true) Enabling web technologies is fast and easy with PHP, but becomes fastly hardly to manage: - big script with HTML mixed with PHP - very difficult to maintain - very time consuming to upgrade or change due to new requirements - many scripts (sometimes written by different developers with different styles) Adding templating to PHP and MySQL the content is separated from the GUI, and just “plugged-in” with a template engine. BUT IS NOT ENOUGHT TO LET PHP/MySQL BE READY FOR BIG PROJECTS (ex: enterprise solutions) - Business logic must be decoupled from data retrieving - Configuration/Deployment must be made easy and easily reconfigurable - Component programming is a must, this can be realized using Object Oriented Programming and Pattern Design reuse. PHP + MySQL + templating <?php class Cart { var $items; Object Oriented PHP4 // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; A class is a collection of } else { variables and functions working return false; with these variables. A class is } defined using the following } } ?> syntax: OO Example Now we use the Cart the class: 1: 2: 3: 4: 5: 6: <?php $cart = new Cart; $cart->add_item("10", 1); $another_cart = new Cart; $another_cart->add_item("0815", 3); ?> line 2: we ISTANTIATE the class, obtaining an istance in variable $cart line 3: we use method add_item to add an item to the cart line 4: we “create” a new Cart, storing the reference in variable $another_cart line 5: using method add_item we add an item to the second cart Now we use inheritance to extend out class, adding new functionalities 1: 2: 3: 4: 5: 6: 7: 8: 9: <?php require(‘Cart.php’); class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } ?> OO Example (II) line 2:We require another file, the one containing the class Cart line 3: A new class is defined as an extension of existing Cart line 4: another variable is specified line 5: another method is specified line 6: $this is a reference to the current object OO Example (III) 1: 2: 3: 4: 5: 6: 7: <?php require(‘Named_Cart.php’); $ncart = new Named_Cart; $ncart->set_owner("kris"); print $ncart->owner; $ncart->add_item("10", 1); ?> line 2: We require the file containing the new cart class line 3: Create a named cart istance line 4: print the Cart owner name line 5: add an item using inherited method from cart class Abstraction Layers The abstraction layer decouple the above layer from the layer below making transparent the change of one of them to the other of them. In PHP development a good DB Abstraction layer allows the PHP script not to care about the Data Access. Using PEAR::DB, allows the canche to change the Database canching any line of the php script. php script php script A.Layer Data access Data access DB Abstraction Layers an example! <?php require_once 'DB.php'; $db = DB::connect('mysql://user:pw@host/mydb'); $stmt = $db->prepare('SELECT * FROM comments'); $result = $db->execute($stmt); while($row = $db->fetchrow($result)) { while($row as $field => $value ) { echo "$field: $value<br>\n"; } } $db->disconnect(); ?> Abstracting the abstraction We sow how to use PEAR::DB as Database Abstraction Layer. After some time develping with PEAR::DB you understand that: - Many piece of code are used and reused many times - All this code is easily copies & pasted but some environmental differences makes the maintenance more difficult - when you find a smarted approach in solving a problem, if you need to use it in all your scripts you need to do it in all of them (usually not easy to do with search & replace features, due to small changes in variable names, and anyway not reliable) The solutions is to create another abstraction layer addressing all this needed functionalities. We will use PEAR::DB_DataObject DB_DataObject DataObject allows to speed-up development in different ways: - creating automatically PHP code. It creates a new script containing a class for each table - creating abstract Application Programming Interfaces (API) on top of PEAR::DB API to simplify developers life example.php DB_DataObject* PEAR::DB (* DB_DataObject uses not only PEAR::DB Interfaces but also object extension features) Data access DB_DataObject configuration (I) Create a DataObject folder into your script folder, and save a file called db_dataobject.ini there. An example follows: [DB_DataObject] ; PEAR::DB DSN database = mysql://user:pwd@db_server/db_name ;sitepoint.ini schema location schema_location = /var/www/html/weben_2005/examples/DataObject ;Location where DataObject classes will be created class_location = /var/www/html/weben_2005/examples/DataObject ; Prefix for including files from your code require_prefix = weben_2005/examples/DataObject ;Classes should be prefixed with this string class_prefix = DataObject_ ;Debugging information: 0=off, 1=display sql, 2=display results,3=everything debug = 0 ;Prevent SQL Insert, Update and Delete from being performed debug_ignore_updates = false ;Whether to die of error with a PEAR_ERROR_DIE or not dont_die = false DB_DataObject configuration (II) Now using the provided script, DataObject automatically creates the php script containing one class for each database table: - DataObject automatically discover the database structure - for every table create a script containing a class Put the Generator.php script into your examples/DataObject folder. Then from the browser or on command line execute it: localhost:~/htdocs/weben_2005/examples/DataObject$ php Generator.php #!/usr/bin/php -q db_dataobject_generator : 0 : CREATING FOR weben_2005 db_dataobject_generator : 0 db_dataobject_generator : 0 db_dataobject_generator : 0 DataObject/weben_2005.ini db_dataobject_generator db_dataobject_generator db_dataobject_generator : 0 : 0 : 0 : calling generatedefinitions : Generating Definitions file: : Writing ini as /var/www/html/weben_2005/examples/ : calling generateclasses : writing DataObject_Personnel : DONE DB_DataObject an example We sow how to use PEAR::DB as Database Abstraction Layer. After some time develping with PEAR::DB you understand that: - Many piece of code are used and reused many times - All this code is easily copies & pasted but some environmental differences makes the maintenance more difficult - when you find a smarted approach in solving a problem, if you need to use it in all your scripts you need to do it in all of them (usually not easy to do with search & replace features, due to small changes in variable names, and anyway not reliable) The solutions is to create another abstraction layer addressing all this needed functionalities. We will use PEAR::DB_DataObject PHP for “Big” projects What’s a Big project? In my opinion when one or more of the following conditions are true: - Composed by a lot of code, >10.000 lines (without libraries) - Involving at least a team or even more than a team - Involving different professionals, design, development, management, specific business specialist, customers - Must be integrated into a system - Other systems will need to interoperate with it The need of a Frameworks A framework allows a better planning of new projects and usually allows a good separations in development tasks. A php example is FastFrame, uses Object Oriented development and Patter Design features to create a common environment for application development. Model View Control (MVC) paradigm is used that allow the separation of the Model (mapping data access to php classes) to View (how data are displayed into the Graphical User Interface) to Control (the business logic specifically developed for the application) Allows new developers to get used of a project with relative low start-up time. An application developed without a good design (that usually means relying on a framework) will be very difficult or impossible to be managed by other developers without the presence of the original developers. Learning path - Script by script with Mixed HTML/PHP - Template engine and library usage PHP<- Template ->HTML - Object Oriented Programming maximizing code reuse and plugging in open source libraries (try to do it by yourself and at the same time see known solutions). In my opinion the best way to learn to reuse code is wasting some time not reusing code. - Learn Pattern Design for “2nd level” code reuse and add some known Patterns to your code - Learn and use a framework (ex: fastframe, that uses OOP and Pattern Design) to create a complete web application - Now all is moving is automatic code generation starting from models (like UML or UML-style). There are already many Open Source solutions (DataObject itself creates automatically the Data access from the database scheme). Bibliography “Create dynamic sites with PHP & MySQL by Md. Ashraful Anam ” (www.codewalkers.com Resource for PHP and SQL Developers) FastFrame http://www.codejanitor.com PEAR: http://pear.php.net PHP: http://www.php.net MySQL: http://www.mysql.org
Copyright © 2024 DOKUMEN.SITE Inc.