Database
MySQL commands:
$link = mysql_connect("host",:"username", "password"); //$link= FALSE on error, Link Id otherwise. $db = mysql_db_select("database", [$link]); //$db = FALSE on error. $rs = mysql_query("query", [$link]); //Is used for querying like select. $rs = mysql_exec("query", [$link]); //Is used for executing commands like inserting, updating, deleting. $row = mysql_fetch_array($rs); //Resource Id. Fetch as an index array. $row = mysql_fetch_assoc($rs); //Resource Id. Fetch as an associative array. mysql_close($link); //Close link. mysql_insert_id($rs); //Last insertion Id. mysql_error([$link]); //Last error. //This provides a security feature which prevents security vulnerabilities by escaping characters like quotes. $output = mysql_real_escape_string("unescaped_string", [$link]);
Create new links with MySQL:
To open a new link, we need to make newlink as true. New link is created even if identical calls are made In SQL safe mode this parameter is ignored.
$link = mysql_connect("host",:"username", "password", newlink);
mysqli = MySQL Improved
PHP data objects are:
- used to connect with a large variety of RDBMS.
- secure. This is implemented by Prepare command.
- atomic. It uses beginTransaction, Commit and rollBack for those RDBMS that support transactions.
try { $dsn = ’mysql:host=localhost;dbname=library’; //Dsn Data source name formatted according to the driver used. $dbh = new PDO($dsn, ’dbuser’, ’dbpass’); //Dbh Database handler. $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //By default PDO::ERRMODE_SILENT. So, no exception raised. $dbh->beginTransaction(); //Begins transaction. $affected = $dbh->exec("sql") //For INSERT, UPDATE, or DELETE and return affected rows. $dbh->exec("sql") $dbh->commit(); //Commits transaction. $dbh->rollBack(); //RollBack transaction. $results = $dbh->query($sql); //Returns a PDOStatement object. $results->setFetchMode(PDO::FETCH_OBJ); //PDO::FETCH_BOTH, PDO::FETCH_ARRAY. foreach ($results as $row) { } $sql= "SELECT * FROM table WHERE id = :param1"; //Also ? instead of : for bound parameters. $stmt = $dbh->prepare($sql); //No need of quoting here using PDO:quote(). $stmt->bindParam(’:param1’, $param1); $stmt->setFetchMode(PDO::FETCH_OBJ); $stmt->execute(); $results = $stmt->fetchAll(); foreach ($results as $row) { } } catch (PDOException $e) { echo "Failed: ". $e->getMessage(); }
Persistent connections:
Persistent connections do not close on the execution of script. Also, when a new connection is requested, it looks for an open identical connection (Same username, password and host) and if so, uses it.
- mysql_pconnect();
- mysqli_connect() with p: prefix on host.
- While creating PDO object use PDO::ATTR_PERSISTENT as a driver option Driver option is the fourth and final parameter and is an array of options.
Web Service
- Web Service is a standard way of interoperating between different software applications running on variety of platforms and/or frameworks.
- SOAP – Simple Object Access Protocol.
- RPC – Remote Procedure Call. It is the most common messaging pattern.
- REST – Representational State Transfer. Each resource must be identified by a global identifier URI. To access these resources, clients communicate with the REST service by HTTP, and the server responds with a representation of the resource. They are not discoverable and hence has no WSDL. Websites that give RSS and RDFfeeds provide RESTful service. Delicious is an example which gives an XML ready to be consumed by SimpleXML. We pass the URL the username and password to obtain XML.
- WSDL – Web Services Definition Language. It is a language for locating and describing web services.
- UDDP – Universal Description Discovery and Integration. It is a directory service where we can register and search web services
- NuSoap is a famous SOAP library in PHP.
Server:
//We have to first code the class MySoapServer with a function named method with parameter param and locate this code in server.php. $options = array(uri' => http://example.org/soap/server/); $server = new SoapServer(NULL, $options); $server->setClass(MySoapServer); $server->handle();
Client:
try { $options = array( location => http://example.org/soap/server/server.php,uri => http://example.org/soap/server/,'trace'=1); $client = new SoapClient(NULL, $options); //WSDL URI if working in WSDL mode with options as next parameter. Here not in WSDL mode so first parameter is NULL and options have to include location an URI. Last parameter with trace=1 will debug. $results = $client->method(param); //Method from WSDL. Returns XML. You can loop through it. echo $client->__getLastRequestHeaders(); //Request headers. echo $client->__getLastRequest(); //Request XML body. } catch (SoapFault $e) { echo $e->getMessage(); }
XML
XML:
- XML is Extended Markup Language.
- DTD or Document Type Definition gives information about structure and content of the particular XML.
- An entity is a named storage using like say head tag.
- An element usually has attributes and other texts.
- Finally, there is the content or value of the entity.
SimpleXML:
SimpleXML is a PHP 5 library that takes care of working with XML. Some methods are available after 5.1.3.
$library = new SimpleXMLElement($xmlstr); //Load XML from string. $library = new SimpleXMLElement(library.xml, NULL, true); //Load XML from file. True tells first parameter is a path to the file. foreach ($library->book as $book) //Looping through many books is library. Children. { echo $book[isbn] . "n"; //Accessing an attribute. echo $book->title . "n"; //Accessing a child. } foreach ($library->children() as $child => $valuechild) //Get children of this element. { echo $child->getName()."=".$child; //Example a = this is a link. echo $child."=". $valuechild; //Example a = this is a link. foreach ($child->attributes() as $attr => $valueattr) //Get attributes of this element. { echo $attr->getName()."=".$attr; //Example target = _blank. echo $attr."=". $valueattr; //Example target = _blank. } }
XPATH:
XPath or XML Path Language is a way to access and search XML Documents.
$results = $library->xpath(/library/book/title); //Returns the XML Object under the XPath. $newbook = $book->addChild(title, "Enders Game"); ///Adding a child. Third optional parameter is namespace. $book->addAttribute(isbn, 0812550706); //Adding an attribute. Third optional parameter is namespace. header(Content-type: text/xml); //Header for XML. echo $library->asXML(); //Print XML. //Remove the children of book[0]. You cannot remove an attribute of book. You can only set them to empty. For that to happen we will have to export to DOM and use a powerful functionality there. $library->book[0] = NULL; $namespaces = $library->getDocNamespaces(); //Gets namespaces declared in the root element referenced. By passing true all namespaces declared recursively in children will be returned. foreach ($namespaces as $key => $value) { echo "{$key} => {$value}"; } $namespaces = $library->getNamespaces(true); //Gets namespaces used (not declared) in the root element referenced. Passing True will return all namespaces used recursively in children will be returned.
DOM:
DOM is Document Object Model.
$dom = new DomDocument(); $dom->load(library.xml); //Load from file. $dom->loadXML($xml); //Load from XMl string. $dom->loadHTMLFile("librabry.html"); //Load from HTML file. $dom->loadHTML($html); //Load from HTML string. $dom->saveXML(); //Save as XMl. $dom->saveHTML(); //Save as HTML. $element = $dom->createElement("a", 'This is a link!'); //Creates an element. $element = $dom->getAttribute("target"); //Returns value of attribute. $element = $dom->hasAttribute("target"); //Checks to see if attribute exists. Returns TRUE or FALSE. $element = $dom->setAttribute("target","_blank"); //Adds new attribute. Returns sub-DOM object. $element = $dom->:removeAttribute("target"); //Removes attribute. Returns TRUE or FALSE.
Design Pattern
- Design patterns are just guidelines on how code should be designed for scenarios. It can be procedurally coded or using more favourably using OOPs.
- Singleton Pattern gives access to a single resource not replicated. Here we have private constructor and a static function which creates a resource if and only if no resource exists. it returns the created or existing resource which is stored as a static property. An example here is MySQL connection link resource.
- Factory Pattern creates a factory or generic class which returns instances or objects of separate specialised classes that handles same task separately. Here depending on say function parameter different objects are instantiated and returned. Consider data storage manager which instantiates storage classes depending on say user’s preference. So, he can choose between say INI or DB or XML which are implemented using an interface.
- Registry Pattern creates a pattern where you can register resources and later on check if a resource is registered and retrieve it. Here we add all registered resources to a static property array and check against and retrieves from the array as required. We add say and class and its object as an associative array property.
- MVC or Model-View-Controller is a design pattern where the controller is called by user (even in default action) and it interfaces with model (business logic) to change its state and finally view is called which reflects changes in model.
- Active Record Pattern is a pattern where the data source is encapsulated so that the act of accessing the components is hidden within the class that implements the pattern. An example is we don’t worry about how SQL implements data row writing or fetching.
OO PHP
- Predominantly version 5.
-
class cname { access control modifier $variable; //Known as class property. access control modifier function(){} //Known as class method. } $obj = new cname; //Or $obj = new cname(); $obj->methodname();
- $this variable always points to the object you are currently working with.
- Access control modifiers: public, private, protected, abstract and final.
- If there is an abstract method the class should be abstract.
- instanceof and is_subclass_of( ) =>$poppy instanceof Poodle and is_subclass_of($poppy, “Poodle”);
- classes and interface can be given as hints.
- extends keyword for inheritance.
- __construct() =>Constructor parent should be created initially in the child.
- __destruct() => Destructor parent should be created last from the child.
- parent::.
- unset() to destroy an object => will call destructor.
- clone obj to clone an object.
- In cloning all members will be copied and then __clone() method will be called and it can be overridden.
- == Compares equality of value whereas for === the handler should be same. Problem is if we use == in object comparison then a loop can occur as the object may be self referenced and it searches deeply again and again to get the value for comparison.
- Polymorphism is defined as one interface to control access to a general class of actions. There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions.
- Early binding determines execution path at compilation and late binding allows for dynamic execution at runtime.
- Magic methods:
- __function().
- __sleep() for serialize() and __wakeup() for deserialize.
- __autoload(classname) =>When an object declared prior to definition this function gets called with classname. We can used to include it.
- __get(propname) => If unknown property name is used then this function is called.
- __set(key, value) =>If unknown property is set key and value will be send to this function.
- __call() => If unknown method called then method name passed to this.
- __toString() => If class is used as a string, then this function is invoked.
- Static method calls are compiled at compile time and is accessed using classname::fnname [self]. Static properties can’t be accessed outside static functions.
- class_exists( ), get_class( ), and get_declared_classes( ).
- Overloading is defining functions that have similar signatures, yet have different parameters. Overloading in PHP means to dynamically create properties and methods. They can be processed using magic functions like __call to create various action types.
- Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that function.
- A class is made abstract if it has abstract function both of which require abstract keyword prefixed. They are not defined in the parent class and has been defined in an inherited These methods must be defined with the same (or a less restricted) visibility.
- Interface helps in implementing multiple inheritance. Interface is defined using interface keyword and implemented using implements keyword. Also, all methods must be implemented if interface is implemented. It is a contract to implement all methods.
- Dereferencing means accessing the return refence without first assigning it to an intermediate variable and then accessing through the intermediate variable. Return value dereferencing is allowed only for objects funcreturningobject()->member.
- Lazy loading means loading classes on demand. the PHP interpreter calls __autoload(class) function which can be used to load the class by say including or requiring a path using the class name. SPL additionally provides us a facility to stack autoloaders where next tries to load fails if previous fails. So different schemas like classes in different paths can be loaded.
- Trait allows reuse of code fragments horizontally across classes. We define it using keyword trait to group functions and keyword use is use to substitute it in classes.
- Reflection is an APi set that can reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, the reflection API offers ways to retrieve doc comments for functions, classes and methods.
Functions
- There is no function overloading in PHP rather it may be simulated using __Call__ magic method. This is because PHP functions can take variable-length argument lists. The functions func_num_args( ), func_get_arg( ) and func_get_args( ) help us in this case.
- PHP also provides default parameters.
- $GLOBALS References all variables available in global scope. Use global keyword to access a global variable in a function by importing specific global variable into the local variable table.
- Variable variables $$var.
- Super Globals : $GLOBALS, $_GET, $_POST, $_SESSION, $_COOKIE, $_FILE, $_REQUEST $_SERVER, $_ENV.
- While passing arguments by reference &. Similarly returning also using ampersand operator.
- Anonymous functions or closures are given below. Anonymous functions yield objects o closure class.
-
$area=function ($side) { return $area * $area; } echo $area (5);
- define(“constantname”, value, t/f) where true means case insensitive.
- To check a constant, we use defined(“constantname”).
- To return retrieve value of a constant from a variable holder or a function we use constant($var) where $var = constantname etc.
Strings
- Serialize(), deserialize(), urlencode() and urldecode().
- For % the result has same sign as the first operator.
- Reference operator =& and reference parameter ¶m in signature.
- $f = func1() or func2(); => ($f = func1()) || func2(); which means func2() executes only if func1() returns false. Example: $f=func() or die(); // Remember to put $f.
- Similarly, $f = func1() and func2(); means func2() executes only if func1() returns true.
- The Execution Operator [Backticks ` (left to 1)].
- Variable functions: $func(49);
- If we set mbstring.func_overload =1 or 2 or 4 or combination in php.ini settings then we can overload 1 (“mail”) + 2 (“str”) + 4 (“ereg”) with its multibyte counterpart. So strpos will work as mb_strpos which will perform operation on even non-ASCII text.
- call_user_func(func, para1 …) and call_user_func_array(func, array) => Call Back Functions. If array each element is a parameter. Another way of function call.
- connection_status( ) tells client status. CONNECTION_NORMAL => 1, CONNECTION_ABORTED => 2, CONNECTION_TIMEOUT => 3.
- escapeshellcmd( ) To prevent/reduce risk in shell execution through PHP.
- string exec (string command [, array &output [, int &return_val]]).
- bool function_exists (string function_name ).
- ignore_user_abort(true) Say for user credit card transaction php executes even if user aborts or cron job. Here script ignore user abort and runs in the background.
- string nl2br (string str) Creates <br /> before all.
- string number_format (float num [, int decimals [, string decimal_point, string thousands_sep]]);
- QUERY_STRING + parse_str( ) => For obtaining queried parameter.
- printf(string with format specifier, placeholder1, placeholder2);
- void register_shutdown_function (function callback [, mixed param [, mixed …]]);
- sha1(): Secure Hash Algorithm. Its checksum is: 40-character hexadecimal string. Also, it is one-way encryption.
- string strip_tags (string html_text [, string allowed_tags]) To reduce cross-site scripting XSS.
- string wordwrap(string str [, int line_length [, string break_chara [, bool cut]]]);
Arrays
- Arrays can be constructed using:
- array () construct.
- array operator [].
- Arrays can be printed using:
- print_ r() prints the array data recursively out and can be stored as a string.
- var_dump( ) prints out the data and data type recursively.
- var_export() prints out array data recursively as a PHP script.
- array(key = value) and array[key]=value.
- Merge arrays, e.g., $array3 = $array1 + $array2.
- extract($arr, EXTR_PREFIX_ALL).
- count ($arr,1) will count recursively the number of elements.
- The array cursors: reset(), end(), next(), and prev().