PHP v/s JavaScript

What is PHP?

PHP stands for Hypertext Preprocessor, which is an open source scripting language. It is a server-side scripting language and a powerful tool for creating a dynamic and interactive website.

PHP is an interpreted language, so it doesn?t need compilation. It is specially designed for server-side scripting, which executes on the server. PHP can be easily embedded with HTML files.

Note: PHP is mainly used to develop server-side applications.

It has several advantages that are given below:

  • PHP code can be executed on different platform such as Windows, Linux, UNIX, Solaris, etc.
  • It is easy to use and learn.
  • PHP is an open source language, which means, it is available for free of cost.

In general, PHP is cheap, cross-platform, fast, and reliable to develop web applications.

What is JavaScript?

JavaScript is a client-side scripting language. It is designed to create a network-centric application. JavaScript is a lightweight and case-sensitive language that has object-oriented capabilities.

We can design web pages using HTML, but cannot run any logic like arithmetic operations, check any conditions, or looping statements, etc., so to achieve this at client-side, JavaScript is needed.

JavaScript also has several advantages that are given below:

  • JavaScript is very fast as a JavaScript code executes immediately within the client browser.
  • JavaScript can easily embed with HTML, AJAX, and XML.
  • JavaScript supports all modern browsers and provides the same result on all.
  • It provides immediate feedback to the user if they forgot to enter some details.

Difference between PHP and JavaScript

PHP and JavaScript both are used for different purposes. As we have discussed earlier that PHP is a server-side script, whereas, JavaScript is a client-side script. Below are some differences between PHP and JavaScript has given:

PHPJavaScript
PHP is a server-side scripting language.JavaScript is a client-side scripting language.
PHP performs all the server-side functions like authentication, building custom web content, handling request, etc.JavaScript is designed to create an interactive web application without interacting with the server
PHP can combine with HTML only.JavaScript can combine with HTML, AJAX and also with XML.
PHP is used for back-end purpose only.JavaScript is used for both front-end and back-end.
PHP is easy to learn.JavaScript is complex to learn.
PHP is a multi-threadedlanguage, which means it blocks input/output to do multiple tasks concurrently.JavaScriptis single-threaded, i.e.,event-driven, which means it never blocks, and everything runs in concurrent order.
In PHP, the code will be available and viewed after it is interpreted by the server.A JavaScript code can be viewed Even after the output is interpreted.
It is synchronous by nature and waits for I/O operation to execute.JavaScript is asynchronous by nature and does not wait for I/O operation to execute.

MVC Architecture

MVC is a software architectural pattern for implementing user interfaces on computers. It divides a given application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to, and accepted from the user.

  • MVC stands for “Model view And Controller“.
  • The main aim of MVC Architecture is to separate the Business logic & Application data from the USER interface.
  • Different types of Architectures are available. These are 3-tier Architecture, N-tier Architecture, MVC Architecture, etc.
  • The main advantage of Architecture is Reusability, Security and Increasing the performance of Application.
PHP MVC Architecture

Model: Database operation such as fetch data or update data etc.

View: End-user GUI through which user can interact with system, i.e., HTML, CSS

Controller: Contain Business logic and provide a link between model and view.

Let’s understand this MVC concept in detail:

Model:

  • The Model object knows all about all the data that need to be displayed.
  • The Model represents the application data and business rules that govern to an update of data.
  • Model is not aware about the presentation of data and How the data will be display to the browser.

View:

  • The View represents the presentation of the application.
  • View object refers to the model remains same if there are any modifications in the Business logic.
  • In other words, we can say that it is the responsibility of view to maintain consistency in its presentation and the model changes.

Controller:

  • Whenever the user sends a request for something, it always goes through Controller.
  • A controller is responsible for intercepting the request from view and passes to the model for appropriate action.
  • After the action has been taken on the data, the controller is responsible for directly passes the appropriate view to the user.
  • In graphical user interfaces, controller and view work very closely together.

PHP MySQL Select Query

PHP mysql_query() function is used to execute select query. Since PHP 5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

There are two other MySQLi functions used in select query.

  • mysqli_num_rows(mysqli_result $result): returns number of rows.
  • mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array represents the column name of the table. It return NULL if there are no more rows.

PHP MySQLi Select Query Example

Example

 

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'SELECT * FROM emp4';  
$retval=mysqli_query($conn, $sql);  
  
if(mysqli_num_rows($retval) > 0){  
 while($row = mysqli_fetch_assoc($retval)){  
    echo "EMP ID :{$row['id']}  <br> ".  
         "EMP NAME : {$row['name']} <br> ".  
         "EMP SALARY : {$row['salary']} <br> ".  
         "--------------------------------<br>";  
 } //end of while  
}else{  
echo "0 results";  
}  
mysqli_close($conn);  
?> 

Output:

Connected successfully
EMP ID :1 
EMP NAME : ratan 
EMP SALARY : 9000 
--------------------------------
EMP ID :2 
EMP NAME : karan 
EMP SALARY : 40000 
--------------------------------
EMP ID :3 
EMP NAME : jai 
EMP SALARY : 90000 
--------------------------------

PHP MySQL Create Database

Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Create Database Example

Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'CREATE Database mydb';  
if(mysqli_query( $conn,$sql)){  
  echo "Database mydb created successfully.";  
}else{  
echo "Sorry, database creation failed ".mysqli_error($conn);  
}  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Database mydb created successfully.

PHP MySQL Connect

Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_connect()
  • PDO::__construct()

PHP mysqli_connect()

PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established or null.Syntax

  1. resource mysqli_connect (server, username, password)  

PHP mysqli_close()

PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection is closed or false.

Syntax

  1. bool mysqli_close(resource $resource_link)  

PHP MySQL Connect Example

Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_error());  
}  
echo 'Connected successfully';  
mysqli_close($conn);  
?>  

Output:

Connected successfully

Type Hinting

  • In simple word, type hinting means providing hints to function to only accept the given data type.
  • In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type.
  • In PHP, we can use type hinting for Object, Array and callable data type.

Example 1

<?php  
      
    class a  
    {  
        public $c= "hello javatpoint";  
    }  
    //create function with class name argument  
    function display(a $a1)  
    {  
        //call variable  
        echo $a1->c;  
    }  
    display(new a());  
?>  

Output:

hello protutorials

Example 2

<?php  
      
    class Test1  
    {  
        public $var= "hello protutorials and tech";  
    }  
    //create function with class name argument  
    function typehint(Test1 $t1)  
    {  
        //call variable  
        echo $t1->var;  
    }  
    //call function with call name as a argument  
    typehint(new Test1());  
?>  

Output:

hello protutorials and tech

Overloading

  • Overloading in PHP provides means to dynamically create properties and methods.
  • These dynamic entities are processed via magic methods, one can establish in a class for various action types.
  • All overloading methods must be defined as Public.
  • After creating object for a class, we can access set of entities that are properties or methods not defined within the scope of the class.
  • Such entities are said to be overloaded properties or methods, and the process is called as overloading.
  • For working with these overloaded properties or functions, PHP magic methods are used.
  • Most of the magic methods will be triggered in object context except __callStatic() method which is used in static context.
OVERLOADING

Property overloading

  • PHP property overloading allows us to create dynamic properties in object context.
  • For creating those properties no separate line of code is needed.
  • A property which is associated with class instance, and not declared within the scope of the class, is considered as overloaded property.

Some of the magic methods which is useful for property overloading.

  • __set(): It is triggered while initializing overloaded properties.
  • __get(): It is utilized for reading data from inaccessible Properties.
  • __isset(): This magic method is invoked when we check overloaded properties with isset() function.
  • __unset(): This function will be invoked on using PHP unset() for overloaded properties.

Interface

  • An interface is similar to a class except that it cannot contain code.
  • An interface can define method names and arguments, but not the contents of the methods.
  • Any classes implementing an interface must implement all methods defined by the interface.
  • A class can implement multiple interfaces.
  • An interface is declared using the “interface” keyword.
  • Interfaces can’t maintain Non-abstract methods.

Example 1

<?php  
    interface a  
    {  
        public function dis1();  
    }  
    interface b  
    {  
        public function dis2();  
    }  
  
class demo implements a,b  
{  
    public function dis1()  
    {  
        echo "method 1...";  
    }  
    public function dis2()  
    {  
        echo "method2...";  
    }  
}  
$obj= new demo();  
$obj->dis1();  
$obj->dis2();  
  
?>  

Output:

method 1…method 2…

Example 2

  

<?php  
    interface i1  
    {  
        public function fun1();  
    }  
    interface i2  
    {  
        public function fun2();  
    }  
class cls1 implements i1,i2  
{  
    function fun1()  
    {  
        echo "protutorials";  
    }  
    function fun2()  
    {  
        echo "tech";  
    }  
}  
$obj= new cls1();  
$obj->fun1();  
$obj->fun2();  
  
?>

Output:

protutorialstech

PHP functions

1. get_class: By using this, we can get the class name of an object.

Example 1

<?php  
    class cls1  
    {  
          
    }  
    $obj=new cls1();  
    echo get_class($obj);  
?>  

Output:

cls1

2. get_class_vars: It is used to get all variables of a class as Array elements.

Example 2

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    print_r(get_class_vars("cls1"));  
?>  

Output:

Array([x] => 100[y]=>200)

3. get_class_methods: To get the all methods of a class as an array.

Example 3

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
        function fun2()  
        {  
        }  
    }  
    print_r(get_class_methods("cls1"));  
?>  

Output:

Array([0] => fun1[1] =>fun2 )

4. get_declare_classes: To get the all declare classes in current script along with predefined classes.

Example 4

<?php  
    class cls1  
    {  
      
    }  
    print_r(get_declared_classes());  
?>  

Output:

Some Helpful Functions in PHP to get the Information About Class and Object

5. get_object_vars: To get all variables of an object as an array.

Example 5

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    $obj= new cls1();  
    print_r(get_object_vars($obj));  
?>  

Output:

Array([x] => 100[y]=>200)

6. class_exists: To check whether the specified class is existed or not.

Example 6

<?php  
    class cls1  
    {  
          
    }  
    echo class_exists("cls1");  
?>  

Output:

1

7. is_subclass_of: By using this function we can check whether the 1st class is subclass of 2nd class or not.

Example 7

<?php  
    class cls1  
    {  
          
    }  
    class cls2 extends cls1  
    {  
    }  
    echo is_subclass_of("cls2","cls1");  
?>  

Output:

1

8. method_exists: By using this function we can check whether the class method is existed or not.

Example 8

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
    }  
    echo method_exists("cls1","fun1");  
?>  

Output:

1

Encapsulation in PHP

  • Encapsulation is a concept where we encapsulate all the data and member functions together to form an object.
  • Wrapping up data member and method together into a single unit is called Encapsulation.
  • Encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system.
  • Binding the data with the code that manipulates it.
  • It keeps the data and the code safe from external interference.

Example 1

<?php  
class person  
    {  
      public $name;  
      public $age;  
      function __construct($n, $a)  
         {  
           $this->name=$n;  
           $this->age=$a;  
         }  
public function setAge($ag)  
   {  
   
   $this->ag=$ag;  
   
   }  
   
public function display()  
   
{  
   
    echo  "welcome ".$this->name."<br/>";  
   
    return $this->age-$this->ag;  
   
}  
   
}  
   
$person=new person("sonoo",28);  
   
$person->setAge(1);  
   
echo "You are ".$person->display()." years old";  
   
?>  

Output:

Welcome sonoo

You are 27 years old