Tuesday, September 2, 2014

Output in PHP

12:59 PM Posted by Zayn Ali No comments

This article explains how to correctly use echo and print, single and double quotation marks, dots and commas, explaining the differences and providing examples.

Table of Contents

  1. Echo vs. Print
  2. Single vs. Double quotation marks
  3. Dots vs. Commas
  4. Conclusions

Echo vs. Print

The most common way to output text with PHP is using echo or print. In this section we will see the similarities and the differences between them.

Similarities

  • They are both language constructs (not functions) so they can be used without parentheses:
        echo 'foo';
        // foo
    
        print 'bar';
        // bar
    
  • They can be used to output multiple lines:
        echo 'This is the first line.
              This is the second line.';
        // This is the first line. This is the second line.
    
        print 'As you can see,
               it works with print too.';
        // As you can see, it works with print, too.
    
  • You can concatenate multiple strings using dots (because the dot is an operator that works with string):
        echo 'The concatenation ' . 'works with ' . 'echo...';
        // The concatenation works with echo...
    
        print '...and with ' . 'print ' . 'as well.';
        // ...and with print as well.
    

Differences

  • Only print returns a value (always 1)
  • print can also be used as a function:
        ((1+1) == 2) ? print 'true' : print 'false'
        // true
    
        ((1+1) == 2) ? echo 'true' : echo 'false'
        // Parse error: syntax error, unexpected T_ECHO in outputinphp.php
    
        echo ((1+1) == 2) ? 'true' : 'false'
        // true
    
  • Only with echo you can output multiple parameters separated by a comma (because the comma is part of the echo construct):
        echo 'With echo you can ', 'use the comma ', 'to output multiple parameters.';
        // With echo you can use the comma to output multiple parameters.
    
        print 'With print ', 'you will get ', 'an error.';
        // Parse error: syntax error, unexpected ',' in outputinphp.php
    
Actually, there is no real reason to prefer print over echo (unless if you want the "1" returned by print — and you probably won't need it). As we saw, echo can do all the things that print does, moreover it allows you to use commas instead than dots.
echo is also slightly faster and shorter than print, even if these difference are almost irrelevant.

Single vs. Double quotation marks

In PHP there are two main ways to specify a string: single quotes ('foo') and double quotes ("bar"). There's also a third way — heredoc — but, in this article, we won't talk about it.

Single quotes

When you need to output a plain string, the single quotes are probably the best idea.
Variables and escaped characters (e.g. \n\t\" etc.) will not be expanded, except for \' and \\ (you can also write just a single \ to output the backslash). This will make the parsing of a single quoted string slightly faster than a double quoted one, and you don't have to escape double quotes (e.g. in HTML attributes) as we can see in the following examples:
    echo 'This is a plain string';
    // This is a plain string

    $var = 123;
    echo 'This $var and this \n newline character will not be expanded.';
    // This $var and this \n newline character will not be expanded.

    echo 'The \' single quote and the \\ backslash will be expanded.
    The single \ backslash works too.';
    // The ' single quote and the \ backslash will be expanded.
    // The single \ backslash works too.

    echo "\"test\"";
    // test

    echo "You can also print characters in octal and hexadecimal notation like \141 and \x62.";
    // You can also print characters in octal and hexadecimal notation like a and b.

Double quotes

If you use a double quoted string, variables and escaped characters will be expanded.
    $var = 123;
    echo "This $var will be expanded. You can also use \$var if you want to avoid it.";
    // This 123 will be expanded. You can also use $var if you want to avoid it.

    echo "This characters will be expanded too:\nfoo\n\tbar\nbaz";
    // This characters will be expanded too:
    // foo
    //     bar
    // baz

    echo "\"test\"";
    // test

    echo "You can also print characters in octal and hexadecimal notation like \141 and \x62.";
    // You can also print characters in octal and hexadecimal notation like a and b.
Whenever is possible is better to use single quotes and avoid to include variables inside the strings. Just in few cases — when you have lot of variables that have to be included in a string — the use of double quotes may improve the readability of the code and thus it could be used.

Dots vs. Commas

As we saw in the previous paragraphs, you can use both dots and commas to output strings and variables using echo. Instead, with print, you can only use dots. So, what is the difference between them?
When using dots, all the parts are concatenated to form a single string that will be printed, while with commas, all the parts are printed one by one, without any concatenation.
Using commas is slightly faster than using dots and the output will be exactly the same (no spaces will be added between the arguments as it happens in Python) so there's no real reason to use dots with echo.
    $var = 123;
    echo 'The value of $var is ', $var;
    // The value of $var is 123

    echo 'The value of $var is '.$var;
    // The value of $var is 123
 
    echo "$var * 2 = ", $var*2;
    // 123 * 2 = 246

    echo $var*2, ' is bigger than ', $var;
    // 246 is bigger than 123
Note that, since commas can only be used with echo, you can't use them to concatenate strings like:
    $query = 'SELECT ', $value, ' FROM ', $table, ' WHERE ', $x, ' > 10';
    // Parse error: syntax error, unexpected ',' in outputinphp.php
 
    mysql_query('SELECT ', $value, ' FROM ', $table, ' WHERE ', $x, ' > 10');
    // Warning: Wrong parameter count for mysql_query() in outputinphp.php

Conclusions

We have seen the differences between echo and print, single and double quotes, dots and commas. The following list summarizes all the things that we said in the article:
  • Always use echo instead of print.
  • Never use parentheses with echo.
  • Prefer single quotes if you don't have to expand variables ($var) or escaped characters (like \n).
  • Avoid to include variables inside strings.
  • With echo, use commas instead of dots.
  • Use the dot to concatenate if you are not using echo.

Saturday, August 30, 2014

PHP Validation Class

10:23 PM Posted by Zayn Ali No comments
A simple PHP input validation class. Extend it for extra functionality.

Download the Validation Class from Github


Validation.php

/**
 * Simple Input Validation Class
 * @author Zayn Ali https://www.facebook.com/zaynali53
 * @link   https://github.com/zaynali53/Validation
 */
class Validation {

    protected $errors = array();

    /**
     * Get validation errors for custom display
     * @return array
     */
    public function get_errors() {
        return $this->errors;
    }

    /**
     * Show Ordered/Un-ordered list of Generated Errors
     * @param  array   $attributes
     * @param  boolean $ordered_list
     * @return void
     */
    public function show_errors($attributes = array(), $ordered_list = FALSE) {
        if ( ! is_array($attributes)) {
            trigger_error('show_errors expects $attributes to be an array.');
            return;
        }

        if ( ! is_bool($ordered_list)) {
            trigger_error('show_errors expects $ordered_list to be a boolean.');
            return;
        }

        $tag = ($ordered_list == TRUE) ? "ol" : "ul";
        
        $output = "<$tag";
            foreach ($attributes as $key => $value) {
                $output .= " $key=\"$value\"";
            }
        $output .= ">";

        foreach ($this->errors as $error) {
            $output .= "
  • " . $error . "
  • "; } $output .= ""; echo $output; } /** * Validates the data with the given set of rules * @param array $data * @param array $rules * @return bool */ public function validate($data, $rules) { if ( ! is_array($data)) { trigger_error('validate expects $data to be an array.'); return; } if ( ! is_array($rules)) { trigger_error('validate expects $rules to be an array.'); return; } $valid = TRUE; foreach ($rules as $field_name => $rules_str) { $rules_arr = explode('|', $rules_str); foreach ($rules_arr as $rule) { $value = isset($data[$field_name]) ? $data[$field_name] : NULL; if (preg_match('/:/', $rule)) { $sub_rule = explode(':', $rule); if ($this->$sub_rule[0]($value, $field_name, $sub_rule[1]) === FALSE) $valid = FALSE; } else { if ($this->$rule($value, $field_name) === FALSE) $valid = FALSE; } } } return $valid; } /** * Email filter rule * @param string $value * @param string $field_name * @param string $domain * @return bool */ protected function email($value, $field_name, $domain = NULL) { if ( ! is_null($domain)) { $specific = "@$domain"; $verified = ($specific == substr($value, strpos($value, $specific))); if (filter_var($value, FILTER_VALIDATE_EMAIL) && $verified === FALSE) $this->errors[] = $field_name . " needs to be a valid E-Mail."; return $verified; } $valid = filter_var($value, FILTER_VALIDATE_EMAIL); if ($valid === FALSE) $this->errors[] = $field_name . " needs to be a valid E-Mail."; return $valid; } /** * Required field rule * @param string $value * @param string $field_name * @return bool */ protected function required($value, $field_name) { $valid = !empty($value); if ($valid === FALSE) $this->errors[] = $field_name . " is required."; return $valid; } /** * Minimum Length of the string rule * @param string $value * @param string $field_name * @param int $length * @return bool */ protected function min_length($value, $field_name, $length) { $valid = TRUE; if ( ! is_numeric($length)) { trigger_error('min_length Param: $length must be a number'); return; } if (trim(strlen($value)) < (int) $length) { $valid = FALSE; $this->errors[] = $field_name . " Minimum Length must be " . $length; } return $valid; } /** * Maximum Length of the string rule * @param string $value * @param string $field_name * @param int $length * @return bool */ protected function max_length($value, $field_name, $length) { $valid = TRUE; if ( ! is_numeric($length)) { trigger_error('max_length Param: $length must be a number'); return; } if (trim(strlen($value)) > (int) $length) { $valid = FALSE; $this->errors[] = $field_name . " Maximum Length must be " . $length; } return $valid; } /** * White list filter rule * @param string $value * @param string $field_name * @param string $white_list_string * @return bool */ protected function white_list($value, $field_name, $white_list_string) { $white_list = explode(',', $white_list_string); $valid = in_array($value, $white_list); if ($valid === FALSE) $this->errors[] = $field_name . " is invalid"; return $valid; } }
    Usage of class. Index.php.

    Create a simple form for demonstration.
    
    
        
            
            Validation
        
        
            
    Email:
    Password:
    On the top of Index.php.

    Check the Posted data and then require the validation class.
    Add the validation rules in an array (input field names as keys) and rules as value separating with pipe | and sub-rule with colon :
    Create an object of the Validation class.
    Check if the method validate returns TRUE then echo out the results other wise use get_errors method to display errors.
    if ($_POST) {
        require_once 'class.Validation.php';
    
        $rules = array(
            'email' => 'required|email:zaynali.com',
            'password' => 'required|min_length:8|max_length:30',
            'environment' => 'required|white_list:admin,user,guest'
        );
    
        $validation = new Validation();
    
        if ($validation->validate($_POST, $rules)) {
            // Validated Data
            echo "
    ", print_r($_POST), "
    "; } else { $validation->show_errors(['id' => 'errors', 'class' => 'errors'], TRUE); } }

    What is Inheritance?

    10:05 AM Posted by Zayn Ali No comments

    Inheritance enables new classes to receive—or inherit—the properties and methods of existing classes.


    Object is a self-contained component that contains properties and methods needed to make a certain type of data useful. Class is a blueprint or template to build a specific type of object and that every object is built from a class. Inheritance is a way to express a relationship between blueprints (classes). It's a way of saying: I want to build a new object that is similar to one that already exists, and instead of creating the new class from scratch, I want to reference the existing class and simply indicate what's different.

    Using two concepts of inheritance, sub classing (making a new class based on a previous one) and overriding (changing how a previous class works), you can organize your objects into a hierarchy. Using inheritance to make this hierarchy often creates easier to understand code, but most importantly it allows you to reuse and organize code more effectively.

    In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a super class or base class. A class that inherits from a super class is called a subclass or derived class. The terms parent class and child class are also acceptable terms to use respectively. A child inherits visible properties and methods from its parent while adding additional properties and methods of its own.



    class Person {
        public function print_name($name) {
            echo 'Name: ' . $name;
        }
        
        public function show_class() {
            echo "Class Name: " . get_class($this);
        }
    }
    
    class Student extends Person {
        public function print_name($name) {
            echo 'Student Name: ' . $name;
        }
    }
    
    $person  = new Person();
    $student = new Student();
    
    $person->show_class();            // Output: 'Class Name: Person'
    $person->print_name('Zayn');      // Output: 'Name: Zayn'
    
    $student->show_class();           // Output: 'Class Name: Student'
    $student->print_name('Ali');      // Output: 'Student Name: Ali'
    


    Sub classes and super classes can be understood in terms of the (is a) relationship. A subclass is a more specific instance of a super class. For example, an orange is a citrus fruit, which is a fruit. A shepherd is a dog, which is an animal. A clarinet is a woodwind instrument, which is a musical instrument. If the is a relationship does not exist between a subclass and super class, you should not use inheritance. An orange is a fruit; so it is okay to write an Orange class that is a subclass of a Fruit class.

    Friday, August 29, 2014

    What is Polymorphism?

    12:59 PM Posted by Zayn Ali No comments
     interface Vehicle {
      public function num_wheels();
     }
    
     class Bicycle implements Vehicle {
      public function num_wheels() {
       return 2;
      }
     }
    
     class Car implements Vehicle {
      public function num_wheels() {
       return 4;
      }
     }
    
     class Truck implements Vehicle {
      public function num_wheels() {
       return 18;
      }
     }
    
     $bicycle = new Bicycle();
     $car = new Car();
     $truck = new Truck();
    
     echo "Bicycle: " . $bicycle->num_wheels() . ".
    "; echo "Car: " . $car->num_wheels() . ".
    "; echo "Truck: " . $truck->num_wheels() . ".";


    Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

    The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task. 
    In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

    What is Abstraction?

    12:42 AM Posted by Zayn Ali No comments
    Abstraction is one of the 3 pillars of Object Oriented Programming (OOP). It literally means to perceive an entity in a system or context from a particular perspective. We take out unnecessary details and only focus on aspects that are necessary to that context or system under consideration.

    Here is some good explanation:

    You as a person have different relationships in different roles. When you are at school, then you are a "Student". When you are at work, you are an "Employee". When you are at government institution, you can be viewed as a "Citizen". So it boils down to what in what context are we looking at an entity/object. So if I am modelling a Payroll System, I will look at you as an Employee(PRN, Full Time/Part Time, Designation). If am modelling a Course Enrollment System, then I will consider your aspects and characteristics as a Student(Roll Number, Age, Gender, Course Enrolled). And if I am modelling a Social Security Information System then I will look at your details as a Citizen(like DOB, Gender, Country Of Birth, etc.)

    Difference between Encapsulation and Abstraction:

    Remember that Abstraction(focusing on necessary details) is different from Encapsulation(hiding details from the outer world). Encapsulation means hiding the details of the object and providing a decent interface for the entities in outer world to interact with that object or entity. For example, if someone want to know my name then he cannot directly access my brain cells to get to know what is my name. Instead that person will either ask my name. If a driver wants to speed up a vehicle then there is an interface(accelerator pedal, gear, etc) for that purpose.

    Tuesday, August 26, 2014

    PHP Pagination

    12:44 AM Posted by Zayn Ali No comments
    Pagination script by zayn


    Setting up the database. Save file as "Pagination.sql" and then import it in PHPMyAdmin Pagination Database created.
    SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
    SET time_zone = "+00:00";
    
    CREATE DATABASE IF NOT EXISTS `pagination` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
    USE `pagination`;
    
    CREATE TABLE IF NOT EXISTS `names` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
    
    INSERT INTO `names` (`id`, `name`) VALUES
    (1, 'ali'),
    (2, 'mohsin'),
    (3, 'yasir'),
    (4, 'zain'),
    (5, 'umar'),
    (6, 'hassan'),
    (7, 'imtiaz'),
    (8, 'nadir'),
    (9, 'usman'),
    (10, 'farooq'),
    (11, 'jameel'),
    (12, 'nouman'),
    (13, 'faisal'),
    (14, 'kashif'),
    (15, 'adnan');
    
    Now the basic pagination Script. Save the file as "Pagination.php"
    /**
     * @author: Zain Ali
     *
     */
    
     // Setting up Query string variable (page) for page number
     $page = isset($_GET['page']) ? (int) $_GET['page'] : 1; 
    
     // Setting up DB connection
     $sqli = new mysqli('localhost', 'root', '', 'pagination');
    
     // Storing total numbers of rows in the variable
     $result = $sqli->query("SELECT * FROM `names`");
     $total_rows = $result->num_rows;
    
     // Setting up Per Page Results
     $per_page_rows = 4;
    
     // Calculating the Last Page Number
     $last_page = ceil($total_rows / $per_page_rows);
    
     // Making sure that page number isn't below 1 or more than our Last page 
     if ($page < 1) { 
      $page = 1;
     } elseif ($page > $last_page) { 
      $page = $last_page;
     }
    
     // Setting up the limit to display results Per Page
     $limit = "LIMIT " . ($page - 1) * $per_page_rows . ", " . $per_page_rows;
    
     $result = $sqli->query("SELECT * FROM `names` " . $limit);
    
    Our Basic Mark Up for our Demo Pagination page "Index.php"
    
    
    
     
     Pagination Script By Zayn
     
    
    
     
    Pagination Script By Zayn

    In the ID Results div. Displaying the results by iterating over the results array which we've fetched from Database.
    // Fetching & displaying Results
    while ($row = $result->fetch_object()) {
     echo $row->name . "
    "; }
    Last in ID links. Displaying the Pagination links.
    // First Page Link
    if ($page != 1) {
     echo "First  ";
    }
    
    // Page Indexes
    for ($i = 1; $i <= $last_page; $i++) {
     if ($page == $i) {
      echo "" . $i . "  ";
     } else {
      echo "" . $i . "  ";   
     }
    }
    
    // Last Page link
    if ($page != $last_page) {
     echo "Last  ";
    }
    
    A little CSS for styling our pagination.
    * {
     font-size: 1.1em;
     font-family: Trebuchet MS;
     font-weight: lighter;
    }
    
    #wrap {
     width: 600px;
     margin: auto;
     padding: 30px;
     background-color: #f4f4f4;
     border: 1px solid black;
    }
    
    #links {
     margin-top: 10px;
     text-align: center;
    }
    
    #results {
     height: 130px;
     border: 1px dashed black;
     padding: 10px;
     background-color: white;
    }
    
    .page-links {
     padding-left: 15px;
     padding-right: 15px;
     border: 1px solid black;
     background-color: #ededed;
     text-decoration: none;
     color: black;
    }
    
    .page-links:hover {
     color: white;
     background-color: #4e5c8e;
    }
    
    .page-links:active {
     background-color: black;
    }