Thursday, 30 November 2017

MySQL Date Time

  • Getting current Date/Time/Timestamp.
  • MySQL Date/Time formatting.
  • Date/Time/Timestamp arithmetic operations.
  • Converting MySQL Date/Time/Timezone.
  • Extracting date from MySQL Temporal Data.
For performing the above operations, MySQL functions required to specify Date/Time types as DATE, DATETIME, and TIMESTAMP. But some of these functions accepts string value, for example, STR_TO_DATE() accepts a string that is to be converted to Date.
Since date time calculation has a challenge over creating a valid result within supported range, these MySQL functions reduce burden as like as PHP Date Time functions, from making temporal data manipulation by our own logic.

Getting Current Date/Time/Timestamp

  • CURDATE() / CURRENT_DATE() – This returns current date in YYYY-MM-DD format if this function is used with a string, or YYYYMMDD if used with an integer value.
  • CURTIME() / CURRENT_TIME() – This returns current time in either HH: MM: SS or HHMMSS format, depends on where this function is invoked.
  • NOW() / CURRENT_TIMESTAMP() – This returns either DateTime value in  YYYY-MM-DD HH: MM: SS or timestamp YYYYMMDDHHMMSS format, depends on where this function is invoked.

MySQL Date/Time Formatting

As like as we have performed date formatting using PHP, MySQL also provides set of functions to work with date format.
  • DATE_FORMAT() – It accepts two parameters, that is, a date value, and the format string which will be a collection of date component specifiers. For example,
    //Output: November 4th, 2008 11:45:00 AM
    SELECT DATE_FORMAT(  '2008-11-04 11:45:00',  '%M %D, %Y %r' );  
  • TIME_FORMAT() – As Like as DATE_FORMAT(), it accepts time to be formatted with the group of specifiers given as the second argument.

Date/Time/Timestamp Arithmetic Operations

MySQL allows performing set of arithmetic operations by using the following functions. These functions accepts two arguments,
  1. Initial date or date time value
  2. Imploded parameter by joining INTERVAL keyword, expression and unit, like,
    INTERVAL_expression_unit
    expression – string denotes the value to be added or subtracted with the initial value.
    unit – unit of the interval like a day, month and etc.
And the functions are,
  • ADDDATE() / DATE_ADD() – Both are performing same functions that are to add the given interval with the initial value.
  • SUBDATE() / DATE_SUB() – Similar to date add functions.
MySQL also supports to perform arithmetic operations between two dates, that is
  • DATEDIFF() – It subtracts one date from another and returns the number of days between two given dates.

Converting MySQL Date/Time/Timezone

Unlike PHP timezone conversion, MySQL provides an inbuilt function to convert timezone.
CONVERT_TZ()  – It accepts three arguments, as, DateTime value, from time zone and to timezone.
TIME_TO_SEC() – This function is used to convert the given time value into a number of seconds.

Extracting date from MySQL Temporal Data

  • DATE() – This function is used to returns date from the given temporal data. For that, it accepts either date or date time value as its argument.
  • EXTRACT() – This function is used to extract the unit of date as specified. For that, it requires two arguments, like, date units like a day, month and etc, and the date value from which the specified unit has to be extracted.
  • TIME() – Works as similar as DATE(), but it extracts time to part from the given temporal data.
MySQL contains a huge list of functions related to date, time and timezone, apart from the above list of operations. For example, it can extract date components like a day of a week, week of a month, the month of the year and etc, by using functions like DAYOFWEEK(), DAYOFYEAR() and etc.

And, other arithmetic functions like PERIOD_ADD() and PERIOD_DIFF() are used to add and subtract specified interval with the year month value given.

PHP Access Modifiers

PHP keywords as Access Control Modifiers

Now, let us have a look at the following list to know about the possible PHP keywords used as access modifiers.
  1. public – class or its members defined with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.
  2. private – class members with this keyword will be accessed within the class itself. It protects members from outside class access with the reference of the class instance.
  3. protected – same as private, except by allowing subclasses to access protected superclass members.
  4. abstract – This keyword can be used only for PHP classes and its functions. For containing abstract functions, a PHP class should be an abstract class.
  5. final – It prevents subclasses to override super class members defined with final keyword.

Access modifiers Usage with PHP Classes, Class Members

Based on the possibility of applying the above list of PHP access modifiers, we can classify them. The following tabular column specifies which keyword could be applied wherein classes, functions or methods.
access modifier classes functions variable
public Not Applicable Applicable Applicable
private Not Applicable Applicable Applicable
protected Not Applicable Applicable Applicable
abstract Applicable Applicable Not Applicable
final Applicable Applicable Not Applicable

public Access Modifier

Before introducing access modifiers in PHP, all classes and its members are treated as public by default. Still, for PHP classes without specifying any access modifiers, then it will be treated as public.
If we specify public, private or protected for a PHP class, then it will cause the parse error. For example, if we define a class as,
public class  {
...
...
}
Then, the following parse error will be displayed to the browser.
Parse error: syntax error, unexpected 'public' (T_PUBLIC) in ...
Similarly, class functions without any access modifiers will be treated as public functions. But, it is good programming practice to specify those functions as public for better understanding.
Unlike PHP classes and functions, we need to specify access modifiers for PHP class variables explicitly. For example, the following code is invalid, which will cause PHP parse error.
class Toys {
$categories = array("puzzles","pull back","remote","soft");
...
}
And, the valid code for defining classes with public variables follows.
class Toys {
public $categories = array("puzzles","pull back","remote","soft");
...
}

private Access Modifier

We can state this keyword only for class variables and function, but not for the class itself, as like as public modifier. PHP class members defined as private cannot be accessed directly by using its instance. For example,
class Toys {
private $categories = array("puzzles","pull back","remote","soft");

public function getToysCategories() {
return $this->categories;
}
}
$objToys = new Toys();
print "<pre>";
print_r($objToys->categories); // invalid
print_r($objToys->getToysCategories());
print "</pre>";
In the above program, Toys class contains a private variable and a public function. Accessing this private variable by using Toys class instance with the line,
print_r($objToys->categories); // invalid
will cause PHP fatal error as,
Fatal error:  Cannot access private property Toys::$categories in ...
But we can access class private variables via any public function of that class. In the above program, we are getting the elements of $categories array variables via getToysCategories() function defined as public.
Note that, all members of a class can be accessed within the class scope by using $this variable.

protected Access Modifier

This keyword is used in a PHP program which is using PHP inheritance. And, it is used to prevent access to PHP classes and its members from anywhere, except from inside the class itself or from inside its subclasses.
With this keyword, PHP classes and its member’s functions cannot be access directly from outside the classes and their subclasses, with the references to their instance.
Consider the following PHP program.
<?php
class Toys {
protected $categories = array("puzzles","pull back","remote","soft");
protected $toys = array(array("name"=>"Mechanical Cars","category"=>"pull back"),
array("name"=>"Jigsaw","category"=>"puzzles"),
array("name"=>"HiTech Cars","category"=>"remote"),
array("name"=>"Teddy Bears","category"=>"soft"),
array("name"=>"Baby pillow","category"=>"soft"),
array("name"=>"Chinese Checker","category"=>"puzzles"),
array("name"=>"Electronic Toys","category"=>"remote"));
protected function getToys() {
for($i=0;$i<count($this->toys);$i++) {
$toys_list[] = $this->toys[$i]["name"];
}
return $toys_list;
}
protected function getToysByCategory($category) {
for($i=0;$i<count($this->toys);$i++) {
if($this->toys[$i]["category"]==$category) 
$toys_list[] = $this->toys[$i]["name"];
}
return $toys_list;
}
}

class SoftToys extends Toys {
protected $category = "soft";
function getToys() {
return $this->getToysByCategory($this->category);
}
}

$objToys = new Toys();
$objSoftToys = new SoftToys();
print "<pre>";
/**Invalid
print_r($objToys->categories);
print_r($objSoftToys->categories);
print_r($objToys->getToys());*/
print_r($objSoftToys->getToys());
print "</pre>";
?>
In this program, we can see some of the statements are commented. These are invalid attempts to access protected members from outside Toys class.
We can access these members, as we have done with private member access by using the public function of a class.

abstract Access Modifier

We can define a PHP class or its function as abstract, but, abstractly is not applicable for class variables. For having at least one abstract function in a PHP class, then that class should be an abstract class.
We cannot access PHP abstract class members with its instance. Because PHP restricts instantiating the abstract class and cause the following error message while creating such instance.
Fatal error: Cannot instantiate abstract class ...
But we can inherit an abstract class. Simply to say, PHP abstract classes are behaving like PHP interfaces. For an abstract class, we cannot contain any abstract function definition. Rather, we should just declare a function. For defining it, we should inherit this abstract class for a non-abstract subclass to have function definition.
Following code is an example of PHP abstract modifier.
abstract class Toys {
public $categories = array("puzzles","pull back","remote","soft");
public $toys = array(array("name"=>"Mechanical Cars","category"=>"pull back"),
array("name"=>"Jigsaw","category"=>"puzzles"),
array("name"=>"HiTech Cars","category"=>"remote"),
array("name"=>"Teddy Bears","category"=>"soft"),
array("name"=>"Baby pillow","category"=>"soft"),
array("name"=>"Chinese Checker","category"=>"puzzles"),
array("name"=>"Electronic Toys","category"=>"remote"));
abstract function getToys();

function getToysByCategory($category) {
for($i=0;$i<count($this->toys);$i++) {
if($this->toys[$i]["category"]==$category) 
$toys_list[] = $this->toys[$i]["name"];
}
return $toys_list;
}
}

class SoftToys extends Toys {
protected $category = "soft";
function getToys() {
return $this->getToysByCategory($this->category);
}
}

$objSoftToys = new SoftToys();
print "<pre>";
print_r($objSoftToys->getToys());
print "</pre>";

final Access Modifier

With PHP final access modifier classes are prevented from inheriting them. If we attempt to derive subclasses from PHP final classes, then the following fatal error will occur to stop program execution.
Fatal error: Class SoftToys may not inherit from final class ...

PHP final keyword should be used for PHP classes and functions, but not for class properties or variables. PHP functions with the final keyword will not be overridden.

  • public scope to make that variable/function available from anywhere, other classes and instances of the object.
  • private scope when you want your variable/function to be visible in its own class only.
  • protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Download

Using jqGrid Control with PHP

It will be integrated with any server-side technologies like PHP, ASP.NET and etc. And, it supports most of the popular databases as such as SQL, MySQL, Oracle and etc. We can integrate twitter bootstrap and jQuery UI Themeroller to view grid UI with good look and feel.

With the support of customized jQuery library functions and AJAX calls, integrating jqGrid for our PHP projects will increase its speed, efficiency and etc. For example, we have seen our own PHP CRUD script a few days before. By using the jqGrid plugin, we can simply create a project with CRUD functionalities with less time and code, comparatively. Not only CRUD, jqGrid provides various features like pagination, sorting records with column order, data mapping, searching and etc.
jqGrid is developed at Triand. For each new version, it is upgraded with latest jQuery libraries and also delivered with advanced features, optimizations, bug fixing and etc.

Loading Data to jqGrid from PHP script

Let us have a simple example to load PHP data for grid UI shown using jqGrid. For that, we need to follow the steps listed below.
  • Include jQuery and jqGrid library files.
  • AJAX call to get data from a PHP page.
  • Load AJAX response text with jqGrid UI.

Include jQuery and jqGrid Library Files.

To use  jqGrid for our PHP script, we need to include the following CSS and Javascript files shown in the following code block.
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css' />
<link rel='stylesheet' type='text/css' href='http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css' />

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type='text/javascript' src='http://www.trirand.com/blog/jqgrid/js/jquery-ui-custom.min.js'></script>        
<script type='text/javascript' src='http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js'></script>
<script type='text/javascript' src='http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js'></script>
Instead of using official website URL, we can make a local copy of these files and specify their path accordingly.

AJAX call for Getting Data from PHP.

For raising an AJAX request to get PHP data as a response text, we can use the following custom Javascript code.
<script>
$(document).ready(function () {
$("#list_records").jqGrid({
url: "getGridData.php",
datatype: "json",
mtype: "GET",
colNames: ["User Id", "User Name", "First Name", "Last Name"],
colModel: [
{ name: "userId",align:"right"},
{ name: "userName"},
{ name: "firstName"},
{ name: "lastName"}
],
pager: "#perpage",
rowNum: 10,
rowList: [10,20],
sortname: "userId",
sortorder: "asc",
height: 'auto',
viewrecords: true,
gridview: true,
caption: ""
});  
});
</script>
This script sends AJAX request with required parameters to the PHP page, getGridData.php. The following code shows PHP script called.
<?php 
$conn = mysql_connect("localhost", "root", "") or die("Connection Error: " . mysql_error()); 
mysql_select_db("phppot_examples") or die("Error connecting to db."); 

$page = $_GET['page']; 
$limit = $_GET['rows']; 
$sidx = $_GET['sidx']; 
$sord = $_GET['sord']; 

if(!$sidx) $sidx =1; 

$result = mysql_query("SELECT COUNT(*) AS count FROM users"); 
$row = mysql_fetch_array($result,MYSQL_ASSOC); 

$count = $row['count']; 
if( $count > 0 && $limit > 0) { 
$total_pages = ceil($count/$limit); 
} else { 
$total_pages = 0; 
} 
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit;
if($start <0) $start = 0; 

$SQL = "SELECT * FROM users ORDER BY $sidx $sord LIMIT $start , $limit"; 
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error()); 

$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]['id']=$row['userId'];
$responce->rows[$i]['cell']=array($row['userId'],$row['userName'],$row['firstName'],$row['lastName']);
$i++;
}
echo json_encode($responce);
?>

This PHP script will get user records from database table in the form of PHP array. This array data will be encoded as an JSON data using PHP json_encode() function. By printing this data in AJAX called PHP page, it will be sent as the response text of the AJAX request generated from a Javascript function. This data will be parsed and loaded into jqGrid. After that, the user records will be seen with the jqGrid UI as shown as below.

Download

PHP Change Password Script

Change password feature in a web application is to let the user change their old password at some periodic interval. It makes the user protect the sensitive pages from hackers.
Some web application fixes some expiration period for user’s password. It forces the user to change the password once the expiration period is elapsed. For example, some banking applications force users to change the password for security.
We are going to see an example to change the password with Javascript validation by, accessing MySQL table.
HTML Code for Change Password Form
This HTML code shows the change password.
<html>
<head>
<title>Change Password</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div style="width:500px;">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
<tr class="tableheader">
<td colspan="2">Change Password</td>
</tr>
<tr>
<td width="40%"><label>Current Password</label></td>
<td width="60%"><input type="password" name="currentPassword" class="txtField"/><span id="currentPassword"  class="required"></span></td>
</tr>
<tr>
<td><label>New Password</label></td>
<td><input type="password" name="newPassword" class="txtField"/><span id="newPassword" class="required"></span></td>
</tr>
<td><label>Confirm Password</label></td>
<td><input type="password" name="confirmPassword" class="txtField"/><span id="confirmPassword" class="required"></span></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body></html>
All the fields are mandatory and the newPassword and confirmPassword should be same. We are using Javascript validation. The validation function is,
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;

currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;

if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}  
return output;
}
</script>

PHP Change Password Script

After successful form submits, the PHP code will access MySQL to get current password. If this database value is matched with the forms current password value, then the password will be changed. The PHP code is,

<?php
$_SESSION["userId"] = "24";
$conn = mysql_connect("localhost","root","");
mysql_select_db("phppot_examples",$conn);
if(count($_POST)>0) {
$result = mysql_query("SELECT *from users WHERE userId='" . $_SESSION["userId"] . "'");
$row=mysql_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysql_query("UPDATE users set password='" . $_POST["newPassword"] . "' WHERE userId='" . $_SESSION["userId"] . "'");
$message = "Password Changed";
} else $message = "Current Password is not correct";
}
?>

Download

PHP try-catch


For each try block in a PHP program, there should be minimum one catch block. We can have multiple catch blocks for a try block, to handle various classes of PHP exceptions.

PHP try-throw-catch Syntax

The following code block shows the usage of try and catch in a PHP program.
<?php
try{
// any code throws exception
}
catch(Exception $e) {
//code to print caught exception
}
?>

Simple PHP Example for try-catch

Let us have a simple PHP try-catch example by using above syntax.
<?php
try{
$get_vars = count($_GET);
if($get_vars!=0) {
foreach($_GET as $key=>$value) {
echo $key . " = " . $value . "<br/>";
}
} else {
throw new Exception("PHP GET global array is empty");
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
In the above example, try block checks the length of the PHP global array variable $_GET to print its element by iterating over PHP foreach block.
If the length of $_GET array is 0, then, an exception will be thrown. The loop and throw statements are handled with if and else part of try block in the above PHP program.

PHP try with Multiple catch

As we have specified at the beginning, multiple catch blocks for single PHP try block is used to handled classified exceptions. For example, PHP library provides separate exception class as LogicException, RunTimeException and etc by inheriting parent Exception class.
The following PHP program contains several conditional blocks throwing a different kind of PHP exceptions accordingly. For example,
<?php
$time_param1 = array(1,2,3,"four",5,6);
try{
$timestamp1 = get_timestamp($time_param1);
print "PHP time stamp - " . $timestamp1 . "<br/>";
}
catch(Exception $e) {
echo $e->getMessage();
}
catch(InvalidArgumentException $e) {
echo $e->getMessage();
}
function get_timestamp($time_param) {
$time_param_length = count($time_param);
if($time_param_length!=0) {
for($i=0;$i<$time_param_length;$i++) {
if(!is_numeric($time_param[$i])) {
throw new InvalidArgumentException("parameter $i should be numeric, " . gettype($time_param[$i]). " is given");
}
}
} else {
throw new Exception("no argument is passed for calculating timestmap");
}
$timestamp = mktime($time_param[0], $time_param[1], $time_param[2], $time_param[3], $time_param[4], $time_param[5]);
return $timestamp; 
}
?>
In this example, we are calculating timestamp value using PHP mktime() with the given array of parameters. Since mktime() accepts numeric values as date co-ordinates, we should evaluate all parameters before the pass into this function.
On performing PHP validation, if anything wrong with the datatype, then InvalidArgumentException will be thrown. In case, if the parameter array is empty, then Exception class instance is used to throw. These two classifications of exceptions are handled with two independent catch blocks provided for a single try block used in this example.

Nested try-catch in PHP

We can create nested PHP blocks to handled subsequent exceptions each occurred by the cause of previous one. For example, if we upload a file, we need to check for its existence. If no such file exists, then will PHP caught file not found an exception and there by cause unable to upload file error.
In such situation, we can use nested try-catch blocks to display an error message regarding all exceptions occurred. For example,
<?php
try{
upload_file("testfile.php");
}
catch (Exception $e){
echo $e->getMessage() . "<br/>";
while($e = $e->getPrevious()) {
echo 'Previous Error: '.$e->getMessage() . "<br/>";
}
}
function upload_file( $filename){
try{
if(file_exists($filename)){
// code for file uploading
} else {
throw new Exception( 'file not found');  
}
}
catch (Exception $e){
throw new Exception( 'unable to upload file',0,$e);
}
}
?>
By passing Exception class’s previous error instance, we can capture nested exception. And, this program will return the following output.
unable to upload file
Previous Error: file not found
Note:

  • Apart from PHP Exception class and its subclasses, we can also create some custom classes to handle exception to catch uncaught exceptions.
  • Not one custom classes, but also we can set a user-defined function as an exception handler function by using set_exception_handler() PHP function.
  • With PHP version 5.5 and above, we can use finally blocks to handle the exception. This blocks will be executed anyway if the exception is thrown or not.

PHP Predefined Error Constants



Let us look into the following table to see the available error constants for the PHP errors classified based on the time of their occurrence.
Fatal Error Warning Notice Parse Error
E_ERROR
runtime error;
cannot be recovered;
will halt execution;
E_WARNING
runtime error;
non-fatal;
wont halt execution;
E_NOTICE
runtime error;
anticipate error caution;
wont halt execution;
E_PARSE
compile time error;
generated by parser;
E_CORE_ERROR
start up error;
generated by PHP core;
E_CORE_WARNING
start up non-fatal error;
generated by PHP core;
   
E_COMPILE_ERROR
compile time error;
generated by Zend Scripting Engine;
E_COMPILE_WARNING
compile time error;
generated by Zend Scripting Engine;
   
E_USER_ERROR
runtime error;
generated by user by trigger_error();
E_USER_WARNING
runtime non-fatal error;
generated by user by trigger_error();
E_USER_NOTICE
similar to E_NOTICE;
generated by user by trigger_error();
 
    E_DEPRECATED
runtime error;
anticipate caution for deprecated methods;
 
    E_USER_DEPRECATED
Like E_DEPRECATED;
generated by user by trigger_error();
 

Other PHP Error Constants

There are some more predefined error constants based on the possibility of error recovery or on providing suggestions to refine our code. These are,
  • E_RECOVERABLE_ERROR – This code is to catch the fatal error by using set_error_handler() function. It will not halt execution unless otherwise the error is not caught by the handler.
  • E_STRICT – This code will display suggestions or warnings if any, to change our code into standard and upgraded form.
  • E_ALL – This code is to display all the available error discussed above as a whole except E_STRICT. But, as of PHP version 5.4.0,  E_STRICT is also included with E_ALL.
These error constants can only be specified with a php.ini file to control the visibility of corresponding error. We can found any combination of their error constants with INI supported operators, that is limited with, bitwise (OR, XOR, AND, NOT) and boolean NOT. For example,
error_reporting = E_ALL | E_STRICT

Meaning that it allows to display the error whether it is either of the above classification including the warning notices that is generated for anticipating cautions to change the code as per the coding standards.

PHP Errors

PHP errors will occur with some improper attempts with PHP scripts like, an invalid line of code execution, an infinite loop that causes default execution time elapse (30 seconds), and etc. Let us start with the major classification of PHP errors as follows.
  1. Fatal error
  2. Parse error
  3. Warning
  4. Notices

Fatal Error

This type of errors is uncaught exceptions that can not be recovered. When this error occurred, then it will stop the execution. Based on the time of occurrence, fatal errors are classified as,
  • Startup fatal error – This will occur when the code cannot be executed with the PHP environment due to the fault that occurred at the time of installation.
  • Compile time fatal error – This kind of error will occur when we attempt to use nonexistent data like file, class, function and etc.
  • Run time fatal error – This will occur during execution. It is similar to compile time fatal error, except Compile time fatal error is generated by the Zend engine based on the time of occurrence.

Example: PHP Fatal Error

Let us call a nonexistent function fnSwap() in the following PHP program.
<?php
fnSwap();
echo "Swapped Successfully!"
?>
This program will raise the following fatal error at the time of execution which will stop executing a further line that is the echo statement.
Fatal error: Call to undefined function fnSwap() in ... on line 2

Parse Error

Parse errors are generated only at compile time which is also called as a syntax error. If anything wrong with PHP syntax, for example, missing semi-colon for the end of the line, will trigger this type of errors to be displayed to the browser.
<?php
echo "content to be displayed to the browser!"
echo "<br/>embedding line break";
?>
This program sends parse error to the browser as follows due to the lack of semicolon(;) at the end of the line.
Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in ... on line 3

Warning

Like fatal errors, PHP warning messages also created based on the three types of warning, that is, Startup warning, Compile time warning and Runtime warning. PHP will create warning message for sending them to the user without halting the execution. An example scenario for warning messages to be created is the divide by zero problem that is as shown in the following PHP program.
<?php
$count = 0;
$total = 200;
$result = $total/$count;
echo "RESULT: ". $result;
?>
In the above program, since $count has the value 0 and any number divided by zero is undefined, the line on which the division is made will create the following warning notices followed by the string returned by the echo statement with an empty value for $result variable. Meaning that, even after the occurrence of the warning error, the echo statement is executed.
Warning: Division by zero in ... on line 4
RESULT:

Notice

Like other PHP error messages, notice message can be created automatically or by the user by using the PHP trigger_error() function.It is used to send messages to the browser to make the user know about the problem of the code is any, which might cause an error.
For example, the following program starts with incrementing an uninitialized variable $result to print incremented value to the browser. Since $result is not initialized, it will automatically trigger the notice error on executing this script.
<?php
$result += 1;
echo "RESULT: ". $result;
?>
And the notice is,
Notice: Undefined variable: result in ... on line 2
RESULT: 1
But program execution will not be terminated because of this PHP notice. Rather, the notice message will be sent to the browser and the echo statement will print the incremented $result value subsequently.

Note:

  • These are set of predefined error constants in PHP, like, E_ERROR, E_WARNING, E_NOTICE, E_PARSE and etc. Each of them is defined with integer value appropriately. For example, the integer value that is defined for E_ERROR is 1.
  • These error constants are required to be specified with PHP configuration file (php.ini) to display various type of PHP errors while execution.
  • On the other hand, we can override error reporting settings at run time by using the PHP error_reporting() function.
  • Another alternative way of overriding error related directive setting on configuration file is, by enabling PHP flags with the .htaccess file. For example,
    php_flag display_errors on