SlideShare a Scribd company logo
PHPAND MYSQL
AISHWARYA
ASSISTANT PROFESSOR
WHAT IS PHP?
PHP is an open-source, interpreted, and object-oriented
scripting language that can be executed at the server-side.
PHP is well suited for web development. Therefore, it is
used to develop web applications (an application that
executes on the server and generates the dynamic page.).
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for
compilation.
o PHP is faster than other scripting languages, for example, ASP
and JSP.
o PHP is a server-side scripting language, which is used to
manage the dynamic content of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language
PHP CODE (ON SERVER)
<?php
echo "The current time is: " . date("h:i:s A");
?>
JSP CODE(ON SERVER)
<%@ page import="java.util.*" %>
<%
Date date = new Date();
out.println("The current time is: " + date.toString());
%>
BUILDING A CONTACT FORM
<form method="POST" action="contact.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
<?php
$name = $_POST['name’];
$email = $_POST['email’];
$message = $_POST['message’];
if (!empty($name) && !empty($email) && !empty($message))
{ echo "Thank you, $name. Your message has been received.";
echo "We will contact you at $email.";
}
Else
{
echo "All fields are required.";
}?>
contact.php
Output:
User enters:
Name: John
Email: john@example.com
Message: Hello, I need help.
After clicking submit button
Thank you, John. Your message has been
received. We will contact you at
john@example.com.
HISTORY OF PHP
PHP (Hypertext Preprocessor), originally standing for "Personal Home Page," is a widely-used open-source
server-side scripting language primarily designed for web development. It was created by Rasmus Lerdorf in
1994 as a set of Common Gateway Interface (CGI) binaries written in C to manage his personal website. Over
time, PHP evolved significantly:
1. PHP/FI (Forms Interpreter) 2.0 (1997): The first major version of PHP was developed to handle forms and
interact with databases. This version laid the foundation for the language's growth.
2. PHP 3 (1997): Israeli developers Zeev Suraski and Andi Gutman's rewrote PHP's parser in C, resulting in
PHP 3. This version dramatically improved performance and capabilities, making PHP more robust and
efficient.
3. PHP 4 (2000): PHP 4 introduced support for object-oriented programming (OOP), which
allowed developers to write more structured, reusable code. It also included many performance
improvements, shaping PHP into a modern language.
4. PHP 5 (2004): This version further improved OOP support, adding features like interfaces,
abstract classes, and exception handling. PHP 5 became a key version for enterprise-level web
applications.
5. PHP 7 (2015): PHP 7 was a major performance upgrade, making it up to twice as fast as
PHP 5.x. It also introduced new features such as scalar type declarations and return type
declarations, improving code clarity and reliability.
6. PHP 8 (2020): PHP 8 introduced Just-In-Time (JIT) compilation, which improved execution
speed for certain types of code. It also brought new features and enhancements such as named
arguments, union types, and match expressions, strengthening PHP’s capabilities for modern
development.
FEATURES OF PHP
Performance: PHP script is executed much faster than those scripts which are written in
other languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and better
performance.
Open Source: PHP source code and software are freely available on the web. You can
develop all the versions of PHP according to your requirement without paying any cost. All
its components are free to download and use.
Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
Embedded: PHP code can be easily embedded within HTML tags and script.
Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in other
OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC,
etc.
Error Reporting - PHP has predefined error reporting constants to generate an error notice or
warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It
will be taken automatically at the time of execution based on the type of data it contains on its
value.
Security: PHP is a secure language to develop the website. It consists of multiple layers of
security to prevent threads and malicious attacks.
WHITE SPACE
White Space is a property defined in CSS (Cascading Style Sheets) that enable the user to control the text
wrapping and white spaces inside an element of the website. It can take several types of values depending
upon the user's need.
Syntax of White Space Property
The syntax of implementing the white-space property in CSS is similar to any other property that is
property_name: value;
1. white-space: value;
Several values that can be passed to the white-space property are:
1. white-space: normal;
2. white-space: nowrap;
3. white-space: pre;
4. white-space: pre-wrap;
5. white-space: pre-line;
6. white space: break-spaces;
1.(normal wrapping):
Text will wrap to the next line when it hits the edge of the container.
The text fits inside the box.
2. (nowrap):
The text does not wrap and stays on one line.
If the text is too long, it will overflow outside the box.
Example:
<?php
$text = "This is a long sentence that might not fit in the box.";
?>
Php and MySQL final year bca notes for bca.pptx
3.(pre):
Spaces and line breaks are preserved.
The text does not wrap to the next line, so it overflows if it’s too long for the container.
4.(pre-wrap):
Spaces and line breaks are preserved.
The text wraps to the next line when it reaches the container's edge.
Example:
<?php
// Text with extra spaces and line breaks
$text = "This is an example with:nn1. Extra spacesn2. Line breaksn3. Long
text that might overflow.";
?>
Php and MySQL final year bca notes for bca.pptx
5.(pre-line):
Collapses multiple spaces into a single space.
Preserves line breaks in the text.
The text wraps within the container.
Example: "This is an example with:“
6. (break-spaces):
Preserves all spaces exactly as written (does not collapse spaces).
Preserves line breaks.
Spaces at the end of the line are also preserved.
Example: "This is an example with:“
Example:
<?php
// Text with extra spaces and line breaks
$text = "This is an example with:nn1. Extra spacesn2. Line breaksn3. Long
text with spaces.";
?>
Php and MySQL final year bca notes for bca.pptx
Commenting in PHP :
Single-line comments:
1. Single-line comments are generally used for short explanations or notes
relevant to the local code.
2. There are two syntaxes for single-line comments in PHP:
 Using #:
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
Multi-line comments:
1. Multi-line comments are generally used to provide pseudocode algorithms and
more detailed explanations when necessary.
2. The syntax for multi-line comments in PHP is the same as in CHere's an
example:
<?
/* This is a comment with multiline
Author: Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
PHP DATA TYPES
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types
that can be categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
PHP Data Types: Scalar Types
It holds only single value. There are 4 scalar data types in PHP.
4. boolean
5. integer
6. float
7. string
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or
FALSE (0). It is often used with conditional statements. If the condition is correct, it returns
TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., 2^31 to
2^31.
o Example: 5, -10, 0
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated
differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types
in PHP.
1.array
2.object
PHPArray
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes);
4. echo "Array Element1: $bikes[0] </br>";
5. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?> Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly
declared. Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Bike Model: Royal Enfield
PHP Data Types: Special Types
There are 2 special data types in PHP.
1. resource
2. NULL
PHP Resource
Resources are not the exact data type in PHP.
Basically, these are used to store some function calls
or references to external PHP resources.
For example - a database call. It is an external
resource
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
Keyword in PHP
 In PHP, keywords are words that have special meanings in the
language and are reserved for specific purposes.
 These words cannot be used as identifiers (such as variable names,
function names, or class
names) in your PHP code, because they are already reserved for built-
in functionality.
Examples: echo, if, else, foreach, class etc…
Control Flow Keywords
• if: Used for decision-making.
• else: Executes code if the if condition is false.
• elseif: Adds another condition to an if statement.
• switch: Tests a variable against multiple values.
• case: Defines a condition inside a switch.
• default: Provides a default action in a switch.
• for: Loop that repeats a block of code a specific number of times.
• foreach: Loop for iterating over arrays.
• while: Loop that repeats as long as a condition is true.
• do: Executes a loop at least once before checking the condition.
• break: Exits a loop or switch.
• continue: Skips the rest of the current loop iteration.
Class and Object Keywords
• class: Defines a blueprint for creating objects.
• public: Makes properties or methods accessible everywhere.
• private: Restricts access to properties/methods to the class itself.
• protected: Allows access within the class and its children.
• new: Creates a new object.
• extends: Inherits a class.
• implements: Implements an interface.
• this: Refers to the current object.
• self: Refers to the current class.
Function Keywords
• function: Defines reusable code (a function).
• return: Sends a value back from a function.
File Handling Keywords
• include: Includes an external file.
• require: Includes an external file and stops execution if it fails.
• include_once: Includes a file only once.
• require_once: Requires a file only once.
Error Handling Keywords
• try: Starts a block of code to test for errors.
• catch: Handles errors thrown in a try block.
• finally: Code that always executes after try/catch.
• throw: Manually triggers an exception.
Miscellaneous Keywords
• echo: Outputs text or data.
• print: Outputs text or data (similar to echo).
• isset: Checks if a variable is set and not null.
• unset: Destroys a variable.
• empty: Checks if a variable is empty.
• die / exit: Stops script execution.
• global: Accesses a global variable inside a function.
• static: Retains a variable's value between function calls.
• abstract: Defines a class/method that must be implemented in a
child class.
• final: Prevents a class or method from being overridden.
PHP VARIABLES
In PHP, a variable is declared using a $ sign followed by the variable name.
Syntax:$variablename=value;
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
PHP EXPRESSION
Almost everything in a PHP script is an expression. Anything that has a value is an
expression. In a typical assignment statement ($x=100), a literal value, a function or
operands processed by operators is an expression, anything that appears to the right of
assignment operator (=)
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression $var=$x!=$y; //$x!=$y is an expression
1. String Functions
• strlen($string) – Gets the length of a string.
• strtolower($string) – Converts a string to lowercase.
• strtoupper($string) – Converts a string to uppercase.
• substr($string, $start, $length) – Extracts a substring.
• str_replace($search, $replace, $subject) – Replaces occurrences in a
string.
2. Array Functions
• array_merge($array1, $array2) – Merges two or more arrays.
• array_push($array, $value) – Adds one or more elements to the
end of an array.
• array_pop($array) – Removes the last element of an array.
• count($array) – Counts the elements in an array.
• in_array($value, $array) – Checks if a value exists in an array.
3. Mathematical Functions
• abs($number) – Returns the absolute value of a number.
• pow($base, $exp) – Returns the result of a number raised to the
power.
• sqrt($number) – Calculates the square root.
• rand($min, $max) – Generates a random integer.
• max($array) – Finds the largest value in an array.
4. File Handling Functions
• fopen($filename, $mode) – Opens a file.
• fwrite($file, $string) – Writes to a file.
• fread($file, $length) – Reads from a file.
• fclose($file) – Closes an open file.
• file_exists($filename) – Checks if a file exists.
5. Database Functions (MySQL)
• mysqli_connect($host, $user, $password, $database) – Connects to
a MySQL database.
• mysqli_query($connection, $query) – Executes a MySQL query.
• mysqli_fetch_assoc($result) – Fetches a result row as an associative
array.
• mysqli_close($connection) – Closes a database connection.
CLASS
A class is a blueprint or template for creating objects. It defines properties
(variables) and methods (functions) that an object will have.
Syntax:
class ClassName
{
// Properties
public $property1;
public $property2;
// Methods
public function method1()
{
echo "This is method1.";
}
}
class Person {
// Properties
public $name;
public $age;
// Methods
public function introduce()
{
echo "Hi, my name is $this->name, and I am $this->age years old.";
}
}
Object
An object is an instance of a class. After defining a class, you can create
objects that have the properties and behaviors defined by the class.
Syntax:
// Create an object
$object = new ClassName();
// Access properties
$object->property1 = "Value";
// Call methods
$object->method1
class Person {
public $name; // Property for name
public $age; // Property for age
public function introduce()
{
echo "Hi, my name is $this->name, and I am $this->age years old.";
}
}
// Create an object
$person1 = new Person();// Assign values to properties
$person1->name = "John";
$person1->age = 24;
// Call the method
$person1->introduce(); // Output: Hi, my name is John, and I am 24 years old.
Steps to Create a Class and Object:
Define a Class: Use the class keyword to create a blueprint (class).
2. Add Properties and Methods: Define the attributes (properties) and behaviors
(methods) of the class
3. Create an Object: Use the new keyword to create an instance (object) of the
class.
4. Access Properties and Methods: Use the -> operator to access an object's
properties and methods.
Step 1: Define a Class
class Animal
{
public $name; // Property for the animal's name
public $sound; // Property for the animal's sound
// Method to describe the animal
public function describe()
{
echo "This is a $this->name and it says $this->sound.";
}
}
Step 2: Create an Object
$cat = new Animal();
// Create an object of the Animal class
Step 3: Assign Values
$cat->name = "Cat"; // Assign "Cat" to the name property
$cat->sound = "Meow"; // Assign "Meow" to the sound
property
Step 4: Call the Method
$cat->describe(); // Output: This is a Cat and it says Meow.
Access Modifiers
A public method is a function defined within a class that can be accessed from anywhere: inside the
class, outside the class, and even in subclasses.
Simple Example
:class Greeting
{
// Public method
public function sayHello()
{
echo "Hello, World!";
}
}
// Creating an object of the Greeting
class$greet = new Greeting();// Calling the public method from outside the class
$greet->sayHello(); // Output: Hello, World!
it.
class Car {
// Private method
private function startEngine()
{
echo "Engine started!";
}
// Public method to use the private method
public function drive()
{
$this->startEngine(); // Calling the private method inside the class
echo " Driving the car!";
}
}
// Create an object of the Car class
$myCar = new Car();
// Accessing the public method that calls the private method
$myCar->drive(); // Output: Engine started! Driving the car!
// Trying to directly access the private method will cause an error//
$myCar->startEngine();
// Error: Cannot call private method
Protected methods are useful when you want to allow subclasses to inherit and use a method but prevent it from
being directly accessed from outside the class hierarchy.
class Car {
// Protected method
protected function startEngine() {
echo "Engine started!";
}
// Public method to call the protected method
public function drive() {
$this->startEngine(); // Calling the protected method inside the class
echo " Driving the car.";
}
}
class ElectricCar extends Car {
// Accessing the protected method in the child class
public function chargeBattery() {
$this->startEngine(); // Calling protected method from the parent class
echo " Charging the battery.";
}
}
// Create an object of the Car class
$myCar = new Car();
$myCar->drive(); // Output: Engine started! Driving the car.
echo "<br>";
// Create an object of the ElectricCar class
$myElectricCar = new ElectricCar();
$myElectricCar->chargeBattery(); // Output: Engine started! Charging
the battery.
Object Properties
Definition: Variables that belong to an object and define its characteristics or attributes.
Declaration: Declared using public, protected, or private access modifiers inside a class.
Access: Accessed using the -> operator
Example:
<?phpclass Animal {
public $name; // Property to store the name
// Method to set the name
public function setName($name) {
$this->name = $name;
}
// Method to get the name
public function getName() {
return $this->name;
}
}
// Create an object of the Animal class
$animal = new Animal();// Set the property value
$animal->setName("Elephant");// Access and display the property
value
echo "Animal Name: " .
$animal->getName();
?>
Object Methods
Definition: Functions defined inside a class that represent the behaviors or actions of an object.
Declaration: Declared using public, protected, or private access modifiers inside a class.
Access: Called using the -> operator.
Example:
class Calculator {
public function add($a, $b)
{
return $a + $b;
}
public function multiply($a, $b)
{
return $a * $b;
}
}
$calc = new Calculator();
echo $calc->add(5, 3); // Calling the add method
echo $calc->multiply(5, 3); // Calling the multiply method
In PHP, method overloading is achieved using magic methods like __call() and __callStatic().
PHP does not support traditional method overloading (defining multiple methods with the same
name but different parameters) as in some other languages like Java or C++.Instead, PHP uses
dynamic handling of method calls to simulate overloading.
METHOD OVERLOADING
How Overloading Works in PHP:
1. Magic Methods
• __call($name, $arguments)Triggered when a call is made to an inaccessible or undefined
non-static method.
• __callStatic($name, $arguments)Triggered when a call is made to an inaccessible or
undefined static method.
2. Dynamic Execution: These methods allow you to handle method calls dynamically by
interpreting the method name and arguments.
Overloading Using __call
class Calculator {
// Magic method to handle dynamic method calls
public function __call($name, $arguments)
{
if ($name == 'add’)
{
return array_sum($arguments); // Adds all the arguments
}
elseif ($name == 'multiply’)
{
return array_product($arguments); // Multiplies all the arguments
}
return "Method $name not defined.";
}
}
// Create an object of Calculator
$calc = new Calculator();
// Dynamic method calls
echo $calc->add(2, 3, 4); // Output: 9
echo "n";
echo $calc->multiply(2, 3, 4); // Output: 24
echo "n";
echo $calc->subtract(5, 2); // Output: Method subtract not defined.
Overloading using __callStatic
class Math {
// Magic method to handle static method calls
public static function __callStatic($name, $arguments)
{
if ($name == 'power’)
{
return pow($arguments[0], $arguments[1]); // Computes power
}
return "Static method $name not defined.";
}
}// Dynamic static method calls
echo Math::power(2, 3); // Output: 8
echo "n";
echo Math::sqrt(16); // Output: Static method sqrt not defined
Property Overloading in PHP
Property overloading in PHP refers to the ability to dynamically create,
retrieve, update, or delete properties that are not explicitly defined in a class.
This is done using magic methods such as __set(), __get(), __isset(), and
__unset().
Magic Methods for Property Overloading
1. __set($name, $value)Called when setting a value to an undefined or
inaccessible property.
2. __get($name)Called when accessing an undefined or inaccessible property.
3. __isset($name)Called when using isset() or empty() on an undefined or
inaccessible property.
4. __unset($name)Called when unset() is used on an undefined or inaccessible
property
class Person {
private $data = []; // Store undefined properties
// Handle setting undefined properties
public function __set($name, $value) {
echo "Setting '$name' to '$value'.n";
$this->data[$name] = $value;
}
// Handle getting undefined properties
public function __get($name) {
echo "Getting '$name'.n";
return $this->data[$name] ?? "Property '$name' not set.";
}
// Handle checking undefined properties
public function __isset($name) {
echo "Checking if '$name' is set.n";
return isset($this->data[$name]);
}
// Handle unsetting undefined properties
public function __unset($name) {
echo "Unsetting '$name'.n";
unset($this->data[$name]);
}
}
$person = new Person();
$person->name = "John"; // __set is called
echo $person->name . "n"; // __get is called
echo isset($person->name) . "n"; // __isset is called
unset($person->name); // __unset is calledecho
$person->name . "n"; // __get is called
Output:
Setting 'name' to 'John’.
Getting 'name’ John
Checking if 'name' is set.1
Unsetting 'name’.
Getting 'name’.
Property 'name' not set.
Inheritance in PHP
• Inheritance allows a class to inherit properties and methods from
another class, promoting code reuse. The class that is inherited
from is called the parent class or base class, and the class that
inherits is called the child class or derived class.
• In PHP, inheritance is primarily single inheritance, but it can
simulate other types through interfaces or traits. Here's an
explanation of the types of inheritance:
Single Inheritance
A child class inherits from only one parent class. PHP does not support multiple inheritance directly to avoid
ambiguity.
class ParentClass {
public function display()
{
echo "This is the parent class.";
}
}
class ChildClass extends ParentClass {
public function show()
{
echo "This is the child class.";
}
}
$child = new ChildClass();
$child->display(); // Inherited from ParentClass
$child->show(); // Defined in ChildClass
2. Multilevel Inheritance
A class inherits from a child class, which in turn inherits from another parent class. This forms a chain of
inheritance.
class GrandParentClass {
public function greet() {
echo "Hello from the grandparent.";
}
}
class ParentClass extends GrandParentClass {
public function welcome() {
echo "Welcome from the parent.";
}
}
class ChildClass extends ParentClass {
public function hello() {
echo "Hello from the child.";
}
}
$child = new ChildClass();
$child->greet(); // From GrandParentClass
$child->welcome(); // From ParentClass
$child->hello(); // From ChildClass
3. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class ParentClass {
public function display() {
echo "This is the parent class.";
}
}
class ChildClass1 extends ParentClass {
public function show() {
echo "This is the first child class.";
}
}
class ChildClass2 extends ParentClass {
public function exhibit() {
echo "This is the second child class.";
}
}
$child1 = new ChildClass1();
$child1->display();
$child1->show();
$child2 = new ChildClass2();
$child2->display();
$child2->exhibit();
4. Multiple Inheritance (via Traits)
PHP does not support multiple inheritance directly but achieves it through traits, which allow a class to inherit
behavior from multiple sources.
trait Trait1 {
public function method1() {
echo "This is from Trait1.";
}
}
trait Trait2 {
public function method2() {
echo "This is from Trait2.";
}
}
class MyClass {
use Trait1, Trait2;
public function method3() {
echo "This is from MyClass.";
}
}
$obj = new MyClass();
$obj->method1(); // From Trait1
$obj->method2(); // From Trait2
$obj->method3(); // From MyClass
Constructor
• A constructor is a method used to initialize an object when it is created.
• It is defined using the __construct() method.
• It can accept parameters to pass initial values to the object.
Syntax:
class ClassName {
public function __construct($param1, $param2)
{
// Initialization code
}
}
Why is a Constructor Used?
1.Automatic Setup: A constructor saves you the trouble of
setting up each object manually.
2.Consistency: It ensures every object starts with proper initial
values or configurations.
3. Convenience: You can pass data to the constructor when
creating the object, and it will use this data to set up the object.
1. Default Constructor
A constructor with no parameters.
Used to initialize default values for an object.
<?phpclass
Person {
public function __construct()
{
echo "Default constructor calledn";
}
}
$obj = new Person(); // Output: Default constructor called?>
2. Parameterized Constructor
A constructor that accepts parameters to initialize an object with specific values <?
phpclass Person {
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
echo "Name: $this->name, Age: $this->agen";
}
}
$obj = new Person("John", 25); // Output: Name: John, Age: 25?>
3. Copy ConstructorIn PHP
• objects are copied by reference, so there isn't a direct implementation of a copy constructor like in some other
languages.
• However, you can manually create a method to copy properties of one object to another.
<?phpclass Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function copy(Person $other) {
$this->name = $other->name;
}
}
$obj1 = new Person("Alice");
$obj2 = new Person("Bob");
$obj2->copy($obj1);
echo $obj2->name; // Output: Alice?>
Destructor
• A destructor is a method that is automatically called when an object is no
longer needed or the script ends.
• It is defined using the __destruct() method.
• Typically used to clean up resources like closing database connections or file
handles.
Syntax:
class ClassName {
public function __destruct() {
// Cleanup code
}
}
<?phpclass Person {
public $name;
public function __construct($name) {
$this->name = $name;
echo "Object created for $this->namen";
}
public function __destruct() {
echo "Object destroyed for $this->namen";
}
}
$obj = new Person("John");// Destructor is called automatically at the end of the script
?>
SQL Commands
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
The MySQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
The MySQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax
DROP DATABASE databasename;
The MySQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name ( column1 datatype,
column2 datatype,
column3 datatype, ....
);
The MySQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing
table in a database.
Syntax
DROP TABLE table_name;
MySQLALTER TABLE Statement
 The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
 The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
The MySQL SELECT Statement
The SELECT statement is used to select data from a database. The data
returned is stored in a result table, called the result-set.
Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select
data from. If you want to select all the fields available in the table, use the
following syntax: SELECT * FROM table_name;
The MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as
the columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
The MySQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
Syntax
DELETE FROM table_name WHERE condition;
Php and MySQL final year bca notes for bca.pptx
UPDATE:
<?php
// Database connection
$conn = mysqli_connect("localhost:3308", "root", "", "demo");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Update query
$sql = "UPDATE student SET course=‘PHP and MYSQL', age=19 WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully.";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>

More Related Content

PPTX
IoT Platforms and Architecture
PPTX
child security wearable device ppt
DOCX
ARDUINO EMBEDDED SYSTEM
PPTX
Software Defined Network - SDN
PPTX
Chapter 4 Embedded System: Application and Domain Specific
PPTX
Smart ambulance
PPTX
Smart garbage monitoring system using internet of things
PPTX
Lecture 5&6 corporate architecture
IoT Platforms and Architecture
child security wearable device ppt
ARDUINO EMBEDDED SYSTEM
Software Defined Network - SDN
Chapter 4 Embedded System: Application and Domain Specific
Smart ambulance
Smart garbage monitoring system using internet of things
Lecture 5&6 corporate architecture

What's hot (20)

PPTX
Touchless touch screen
PPTX
Agribot with leaf detection disease.pptx
PDF
Robotics and ROS
PPTX
Automatic chocolate vending machine using mucos rtos ppt
PPTX
ELEMENTS OF TRANSPORT PROTOCOL
PDF
Project Report Distance measurement system
PPTX
Introduction of Iot and Logical and Physical design of iot
PPTX
Ultrasonic radar mini project
PPTX
Full Stack Web Development
PPTX
women security on IOT
PPTX
Full stack web development
PPTX
Chat App Presentation.pptx
PPTX
blood bank management system project report
PDF
Campus news information system - Android
PPTX
web connectivity in IoT
PPTX
VOICE OPERATED WHEELCHAIR
PDF
Garbage Monitoring System using Arduino
DOCX
Internet of things (iot) based weather
PDF
FINAL YEAR PROJECT ELECTRONICS
PPTX
Ppt 11 - netopeer
Touchless touch screen
Agribot with leaf detection disease.pptx
Robotics and ROS
Automatic chocolate vending machine using mucos rtos ppt
ELEMENTS OF TRANSPORT PROTOCOL
Project Report Distance measurement system
Introduction of Iot and Logical and Physical design of iot
Ultrasonic radar mini project
Full Stack Web Development
women security on IOT
Full stack web development
Chat App Presentation.pptx
blood bank management system project report
Campus news information system - Android
web connectivity in IoT
VOICE OPERATED WHEELCHAIR
Garbage Monitoring System using Arduino
Internet of things (iot) based weather
FINAL YEAR PROJECT ELECTRONICS
Ppt 11 - netopeer
Ad

Similar to Php and MySQL final year bca notes for bca.pptx (20)

PPTX
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
PDF
Introduction to php
PPT
Introduction to php
PPT
php 1
PDF
WT_PHP_PART1.pdf
PPT
PDF
Php introduction
PPTX
PHP Hypertext Preprocessor
PPTX
introduction to php and its uses in daily
PPTX
Web Application Development using PHP Chapter 1
PPTX
Php Unit 1
PPTX
Php unit i
PPTX
Introduction to PHP.pptx
PPTX
Ch1(introduction to php)
PPT
Prersentation
PPT
Php Tutorial
PPTX
Basic of PHP
PPT
Php unit i
PPTX
PHP ITCS 323
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Introduction to php
Introduction to php
php 1
WT_PHP_PART1.pdf
Php introduction
PHP Hypertext Preprocessor
introduction to php and its uses in daily
Web Application Development using PHP Chapter 1
Php Unit 1
Php unit i
Introduction to PHP.pptx
Ch1(introduction to php)
Prersentation
Php Tutorial
Basic of PHP
Php unit i
PHP ITCS 323
Ad

More from AJAYKUMAR34368 (6)

PPTX
THE GREEDY METHOD notes related to education.pptx
PPTX
CHAPTER 1(C) notes related to education.pptx
PPTX
Engnerring documents chapter 134Ch14.pptx
PPTX
Demonstration Of Desktop Computer Hardware Components..pptx
PPTX
C_Program_Adjacency_Matrix_Explanation.pptx
PPTX
Fundamentals of data science notes for bca.pptx
THE GREEDY METHOD notes related to education.pptx
CHAPTER 1(C) notes related to education.pptx
Engnerring documents chapter 134Ch14.pptx
Demonstration Of Desktop Computer Hardware Components..pptx
C_Program_Adjacency_Matrix_Explanation.pptx
Fundamentals of data science notes for bca.pptx

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Trump Administration's workforce development strategy
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
IGGE1 Understanding the Self1234567891011
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Introduction to Building Materials
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
Lesson notes of climatology university.
PDF
Indian roads congress 037 - 2012 Flexible pavement
PDF
Classroom Observation Tools for Teachers
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Computing-Curriculum for Schools in Ghana
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Trump Administration's workforce development strategy
A powerpoint presentation on the Revised K-10 Science Shaping Paper
IGGE1 Understanding the Self1234567891011
Paper A Mock Exam 9_ Attempt review.pdf.
Final Presentation General Medicine 03-08-2024.pptx
LDMMIA Reiki Yoga Finals Review Spring Summer
Final Presentation General Medicine 03-08-2024.pptx
Orientation - ARALprogram of Deped to the Parents.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Introduction to Building Materials
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Hazard Identification & Risk Assessment .pdf
Lesson notes of climatology university.
Indian roads congress 037 - 2012 Flexible pavement
Classroom Observation Tools for Teachers
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3

Php and MySQL final year bca notes for bca.pptx

  • 2. WHAT IS PHP? PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an application that executes on the server and generates the dynamic page.).
  • 3. o PHP stands for Hypertext Preprocessor. o PHP is an interpreted language, i.e., there is no need for compilation. o PHP is faster than other scripting languages, for example, ASP and JSP. o PHP is a server-side scripting language, which is used to manage the dynamic content of the website. o PHP can be embedded into HTML. o PHP is an object-oriented language. o PHP is an open-source scripting language. o PHP is simple and easy to learn language
  • 4. PHP CODE (ON SERVER) <?php echo "The current time is: " . date("h:i:s A"); ?> JSP CODE(ON SERVER) <%@ page import="java.util.*" %> <% Date date = new Date(); out.println("The current time is: " + date.toString()); %>
  • 5. BUILDING A CONTACT FORM <form method="POST" action="contact.php"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br><br> <label for="message">Message:</label><br> <textarea id="message" name="message" required></textarea><br><br> <input type="submit" value="Submit"> </form>
  • 6. <?php $name = $_POST['name’]; $email = $_POST['email’]; $message = $_POST['message’]; if (!empty($name) && !empty($email) && !empty($message)) { echo "Thank you, $name. Your message has been received."; echo "We will contact you at $email."; } Else { echo "All fields are required."; }?> contact.php
  • 7. Output: User enters: Name: John Email: john@example.com Message: Hello, I need help. After clicking submit button Thank you, John. Your message has been received. We will contact you at john@example.com.
  • 8. HISTORY OF PHP PHP (Hypertext Preprocessor), originally standing for "Personal Home Page," is a widely-used open-source server-side scripting language primarily designed for web development. It was created by Rasmus Lerdorf in 1994 as a set of Common Gateway Interface (CGI) binaries written in C to manage his personal website. Over time, PHP evolved significantly: 1. PHP/FI (Forms Interpreter) 2.0 (1997): The first major version of PHP was developed to handle forms and interact with databases. This version laid the foundation for the language's growth. 2. PHP 3 (1997): Israeli developers Zeev Suraski and Andi Gutman's rewrote PHP's parser in C, resulting in PHP 3. This version dramatically improved performance and capabilities, making PHP more robust and efficient.
  • 9. 3. PHP 4 (2000): PHP 4 introduced support for object-oriented programming (OOP), which allowed developers to write more structured, reusable code. It also included many performance improvements, shaping PHP into a modern language. 4. PHP 5 (2004): This version further improved OOP support, adding features like interfaces, abstract classes, and exception handling. PHP 5 became a key version for enterprise-level web applications. 5. PHP 7 (2015): PHP 7 was a major performance upgrade, making it up to twice as fast as PHP 5.x. It also introduced new features such as scalar type declarations and return type declarations, improving code clarity and reliability. 6. PHP 8 (2020): PHP 8 introduced Just-In-Time (JIT) compilation, which improved execution speed for certain types of code. It also brought new features and enhancements such as named arguments, union types, and match expressions, strengthening PHP’s capabilities for modern development.
  • 11. Performance: PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster processing speed and better performance. Open Source: PHP source code and software are freely available on the web. You can develop all the versions of PHP according to your requirement without paying any cost. All its components are free to download and use. Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding with it. Embedded: PHP code can be easily embedded within HTML tags and script. Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also.
  • 12. Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc. Error Reporting - PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of execution based on the type of data it contains on its value. Security: PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and malicious attacks.
  • 13. WHITE SPACE White Space is a property defined in CSS (Cascading Style Sheets) that enable the user to control the text wrapping and white spaces inside an element of the website. It can take several types of values depending upon the user's need. Syntax of White Space Property The syntax of implementing the white-space property in CSS is similar to any other property that is property_name: value; 1. white-space: value; Several values that can be passed to the white-space property are: 1. white-space: normal; 2. white-space: nowrap; 3. white-space: pre; 4. white-space: pre-wrap; 5. white-space: pre-line; 6. white space: break-spaces;
  • 14. 1.(normal wrapping): Text will wrap to the next line when it hits the edge of the container. The text fits inside the box. 2. (nowrap): The text does not wrap and stays on one line. If the text is too long, it will overflow outside the box. Example: <?php $text = "This is a long sentence that might not fit in the box."; ?>
  • 16. 3.(pre): Spaces and line breaks are preserved. The text does not wrap to the next line, so it overflows if it’s too long for the container. 4.(pre-wrap): Spaces and line breaks are preserved. The text wraps to the next line when it reaches the container's edge. Example: <?php // Text with extra spaces and line breaks $text = "This is an example with:nn1. Extra spacesn2. Line breaksn3. Long text that might overflow."; ?>
  • 18. 5.(pre-line): Collapses multiple spaces into a single space. Preserves line breaks in the text. The text wraps within the container. Example: "This is an example with:“ 6. (break-spaces): Preserves all spaces exactly as written (does not collapse spaces). Preserves line breaks. Spaces at the end of the line are also preserved. Example: "This is an example with:“ Example: <?php // Text with extra spaces and line breaks $text = "This is an example with:nn1. Extra spacesn2. Line breaksn3. Long text with spaces."; ?>
  • 20. Commenting in PHP : Single-line comments: 1. Single-line comments are generally used for short explanations or notes relevant to the local code. 2. There are two syntaxes for single-line comments in PHP:  Using #: <? # This is a comment, and # This is the second line of the comment // This is a comment too. Each style comments only print "An example with single line comments"; ?>
  • 21. Multi-line comments: 1. Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary. 2. The syntax for multi-line comments in PHP is the same as in CHere's an example: <? /* This is a comment with multiline Author: Mohammad Mohtashim Purpose: Multiline Comments Demo Subject: PHP */ print "An example with multi line comments";
  • 22. PHP DATA TYPES PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types: 1. Scalar Types (predefined) 2. Compound Types (user-defined) 3. Special Types PHP Data Types: Scalar Types It holds only single value. There are 4 scalar data types in PHP. 4. boolean 5. integer 6. float 7. string
  • 23. PHP Boolean Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE. Example: 1. <?php 2. if (TRUE) 3. echo "This condition is TRUE."; 4. if (FALSE) 5. echo "This condition is FALSE."; 6. ?> Output: This condition is TRUE.
  • 24. PHP Integer Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without fractional part or decimal points. Rules for integer: o An integer can be either positive or negative. o An integer must not contain decimal point. o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., 2^31 to 2^31. o Example: 5, -10, 0
  • 25. PHP Float A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or decimal point, including a negative or positive sign. Example: 1. <?php 2. $n1 = 19.34; 3. $n2 = 54.472; 4. $sum = $n1 + $n2; 5. echo "Addition of floating numbers: " .$sum; 6. ?> Output: Addition of floating numbers: 73.812
  • 26. PHP String A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters. String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To clarify this, see the example below: Example: 1. <?php 2. $company = "Javatpoint"; 3. //both single and double quote statements will treat different 4. echo "Hello $company"; 5. echo "</br>"; 6. echo 'Hello $company'; 7. ?> Output: Hello Javatpoint Hello $company
  • 27. PHP Data Types: Compound Types It can hold multiple values. There are 2 compound data types in PHP. 1.array 2.object
  • 28. PHPArray An array is a compound data type. It can store multiple values of same data type in a single variable. Example: 1. <?php 2. $bikes = array ("Royal Enfield", "Yamaha", "KTM"); 3. var_dump($bikes); 4. echo "Array Element1: $bikes[0] </br>"; 5. echo "Array Element2: $bikes[1] </br>"; 7. echo "Array Element3: $bikes[2] </br>"; 8. ?> Output: array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" } Array Element1: Royal Enfield Array Element2: Yamaha Array Element3: KTM
  • 29. PHP object Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared. Example: 1. <?php 2. class bike { 3. function model() { 4. $model_name = "Royal Enfield"; 5. echo "Bike Model: " .$model_name; 6. } 7. } 8. $obj = new bike(); 9. $obj -> model(); 10. ?> Output: Bike Model: Royal Enfield
  • 30. PHP Data Types: Special Types There are 2 special data types in PHP. 1. resource 2. NULL PHP Resource Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external PHP resources. For example - a database call. It is an external resource
  • 31. PHP Null Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case sensitive. The special type of data type NULL defined a variable with no value. Example: 1. <?php 2. $nl = NULL; 3. echo $nl; //it will not give any output 4. ?>
  • 32. Keyword in PHP  In PHP, keywords are words that have special meanings in the language and are reserved for specific purposes.  These words cannot be used as identifiers (such as variable names, function names, or class names) in your PHP code, because they are already reserved for built- in functionality. Examples: echo, if, else, foreach, class etc…
  • 33. Control Flow Keywords • if: Used for decision-making. • else: Executes code if the if condition is false. • elseif: Adds another condition to an if statement. • switch: Tests a variable against multiple values. • case: Defines a condition inside a switch. • default: Provides a default action in a switch. • for: Loop that repeats a block of code a specific number of times. • foreach: Loop for iterating over arrays. • while: Loop that repeats as long as a condition is true. • do: Executes a loop at least once before checking the condition. • break: Exits a loop or switch. • continue: Skips the rest of the current loop iteration.
  • 34. Class and Object Keywords • class: Defines a blueprint for creating objects. • public: Makes properties or methods accessible everywhere. • private: Restricts access to properties/methods to the class itself. • protected: Allows access within the class and its children. • new: Creates a new object. • extends: Inherits a class. • implements: Implements an interface. • this: Refers to the current object. • self: Refers to the current class.
  • 35. Function Keywords • function: Defines reusable code (a function). • return: Sends a value back from a function. File Handling Keywords • include: Includes an external file. • require: Includes an external file and stops execution if it fails. • include_once: Includes a file only once. • require_once: Requires a file only once.
  • 36. Error Handling Keywords • try: Starts a block of code to test for errors. • catch: Handles errors thrown in a try block. • finally: Code that always executes after try/catch. • throw: Manually triggers an exception.
  • 37. Miscellaneous Keywords • echo: Outputs text or data. • print: Outputs text or data (similar to echo). • isset: Checks if a variable is set and not null. • unset: Destroys a variable. • empty: Checks if a variable is empty. • die / exit: Stops script execution. • global: Accesses a global variable inside a function. • static: Retains a variable's value between function calls. • abstract: Defines a class/method that must be implemented in a child class. • final: Prevents a class or method from being overridden.
  • 38. PHP VARIABLES In PHP, a variable is declared using a $ sign followed by the variable name. Syntax:$variablename=value; Rules for declaring PHP variable: o A variable must start with a dollar ($) sign, followed by the variable name. o It can only contain alpha-numeric character and underscore (A-z, 0-9, _). o A variable name must start with a letter or underscore (_) character. o A PHP variable name cannot contain spaces. o One thing to be kept in mind that the variable name cannot start with a number or special symbols. o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
  • 39. PHP EXPRESSION Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression, anything that appears to the right of assignment operator (=) Syntax $x=100; //100 is an expression $a=$b+$c; //b+$c is an expression $c=add($a,$b); //add($a,$b) is an expresson $val=sqrt(100); //sqrt(100) is an expression $var=$x!=$y; //$x!=$y is an expression
  • 40. 1. String Functions • strlen($string) – Gets the length of a string. • strtolower($string) – Converts a string to lowercase. • strtoupper($string) – Converts a string to uppercase. • substr($string, $start, $length) – Extracts a substring. • str_replace($search, $replace, $subject) – Replaces occurrences in a string.
  • 41. 2. Array Functions • array_merge($array1, $array2) – Merges two or more arrays. • array_push($array, $value) – Adds one or more elements to the end of an array. • array_pop($array) – Removes the last element of an array. • count($array) – Counts the elements in an array. • in_array($value, $array) – Checks if a value exists in an array.
  • 42. 3. Mathematical Functions • abs($number) – Returns the absolute value of a number. • pow($base, $exp) – Returns the result of a number raised to the power. • sqrt($number) – Calculates the square root. • rand($min, $max) – Generates a random integer. • max($array) – Finds the largest value in an array.
  • 43. 4. File Handling Functions • fopen($filename, $mode) – Opens a file. • fwrite($file, $string) – Writes to a file. • fread($file, $length) – Reads from a file. • fclose($file) – Closes an open file. • file_exists($filename) – Checks if a file exists.
  • 44. 5. Database Functions (MySQL) • mysqli_connect($host, $user, $password, $database) – Connects to a MySQL database. • mysqli_query($connection, $query) – Executes a MySQL query. • mysqli_fetch_assoc($result) – Fetches a result row as an associative array. • mysqli_close($connection) – Closes a database connection.
  • 45. CLASS A class is a blueprint or template for creating objects. It defines properties (variables) and methods (functions) that an object will have. Syntax: class ClassName { // Properties public $property1; public $property2; // Methods public function method1() { echo "This is method1."; } }
  • 46. class Person { // Properties public $name; public $age; // Methods public function introduce() { echo "Hi, my name is $this->name, and I am $this->age years old."; } }
  • 47. Object An object is an instance of a class. After defining a class, you can create objects that have the properties and behaviors defined by the class. Syntax: // Create an object $object = new ClassName(); // Access properties $object->property1 = "Value"; // Call methods $object->method1
  • 48. class Person { public $name; // Property for name public $age; // Property for age public function introduce() { echo "Hi, my name is $this->name, and I am $this->age years old."; } } // Create an object $person1 = new Person();// Assign values to properties $person1->name = "John"; $person1->age = 24; // Call the method $person1->introduce(); // Output: Hi, my name is John, and I am 24 years old.
  • 49. Steps to Create a Class and Object: Define a Class: Use the class keyword to create a blueprint (class). 2. Add Properties and Methods: Define the attributes (properties) and behaviors (methods) of the class 3. Create an Object: Use the new keyword to create an instance (object) of the class. 4. Access Properties and Methods: Use the -> operator to access an object's properties and methods.
  • 50. Step 1: Define a Class class Animal { public $name; // Property for the animal's name public $sound; // Property for the animal's sound // Method to describe the animal public function describe() { echo "This is a $this->name and it says $this->sound."; } }
  • 51. Step 2: Create an Object $cat = new Animal(); // Create an object of the Animal class Step 3: Assign Values $cat->name = "Cat"; // Assign "Cat" to the name property $cat->sound = "Meow"; // Assign "Meow" to the sound property Step 4: Call the Method $cat->describe(); // Output: This is a Cat and it says Meow.
  • 52. Access Modifiers A public method is a function defined within a class that can be accessed from anywhere: inside the class, outside the class, and even in subclasses. Simple Example :class Greeting { // Public method public function sayHello() { echo "Hello, World!"; } } // Creating an object of the Greeting class$greet = new Greeting();// Calling the public method from outside the class $greet->sayHello(); // Output: Hello, World!
  • 53. it. class Car { // Private method private function startEngine() { echo "Engine started!"; } // Public method to use the private method public function drive() { $this->startEngine(); // Calling the private method inside the class echo " Driving the car!"; } } // Create an object of the Car class $myCar = new Car(); // Accessing the public method that calls the private method $myCar->drive(); // Output: Engine started! Driving the car! // Trying to directly access the private method will cause an error// $myCar->startEngine(); // Error: Cannot call private method
  • 54. Protected methods are useful when you want to allow subclasses to inherit and use a method but prevent it from being directly accessed from outside the class hierarchy. class Car { // Protected method protected function startEngine() { echo "Engine started!"; } // Public method to call the protected method public function drive() { $this->startEngine(); // Calling the protected method inside the class echo " Driving the car."; } } class ElectricCar extends Car { // Accessing the protected method in the child class public function chargeBattery() { $this->startEngine(); // Calling protected method from the parent class echo " Charging the battery."; } }
  • 55. // Create an object of the Car class $myCar = new Car(); $myCar->drive(); // Output: Engine started! Driving the car. echo "<br>"; // Create an object of the ElectricCar class $myElectricCar = new ElectricCar(); $myElectricCar->chargeBattery(); // Output: Engine started! Charging the battery.
  • 56. Object Properties Definition: Variables that belong to an object and define its characteristics or attributes. Declaration: Declared using public, protected, or private access modifiers inside a class. Access: Accessed using the -> operator Example: <?phpclass Animal { public $name; // Property to store the name // Method to set the name public function setName($name) { $this->name = $name; } // Method to get the name public function getName() { return $this->name; } }
  • 57. // Create an object of the Animal class $animal = new Animal();// Set the property value $animal->setName("Elephant");// Access and display the property value echo "Animal Name: " . $animal->getName(); ?>
  • 58. Object Methods Definition: Functions defined inside a class that represent the behaviors or actions of an object. Declaration: Declared using public, protected, or private access modifiers inside a class. Access: Called using the -> operator. Example: class Calculator { public function add($a, $b) { return $a + $b; } public function multiply($a, $b) { return $a * $b; } } $calc = new Calculator(); echo $calc->add(5, 3); // Calling the add method echo $calc->multiply(5, 3); // Calling the multiply method
  • 59. In PHP, method overloading is achieved using magic methods like __call() and __callStatic(). PHP does not support traditional method overloading (defining multiple methods with the same name but different parameters) as in some other languages like Java or C++.Instead, PHP uses dynamic handling of method calls to simulate overloading. METHOD OVERLOADING How Overloading Works in PHP: 1. Magic Methods • __call($name, $arguments)Triggered when a call is made to an inaccessible or undefined non-static method. • __callStatic($name, $arguments)Triggered when a call is made to an inaccessible or undefined static method. 2. Dynamic Execution: These methods allow you to handle method calls dynamically by interpreting the method name and arguments.
  • 60. Overloading Using __call class Calculator { // Magic method to handle dynamic method calls public function __call($name, $arguments) { if ($name == 'add’) { return array_sum($arguments); // Adds all the arguments } elseif ($name == 'multiply’) { return array_product($arguments); // Multiplies all the arguments } return "Method $name not defined."; } }
  • 61. // Create an object of Calculator $calc = new Calculator(); // Dynamic method calls echo $calc->add(2, 3, 4); // Output: 9 echo "n"; echo $calc->multiply(2, 3, 4); // Output: 24 echo "n"; echo $calc->subtract(5, 2); // Output: Method subtract not defined.
  • 62. Overloading using __callStatic class Math { // Magic method to handle static method calls public static function __callStatic($name, $arguments) { if ($name == 'power’) { return pow($arguments[0], $arguments[1]); // Computes power } return "Static method $name not defined."; } }// Dynamic static method calls echo Math::power(2, 3); // Output: 8 echo "n"; echo Math::sqrt(16); // Output: Static method sqrt not defined
  • 63. Property Overloading in PHP Property overloading in PHP refers to the ability to dynamically create, retrieve, update, or delete properties that are not explicitly defined in a class. This is done using magic methods such as __set(), __get(), __isset(), and __unset(). Magic Methods for Property Overloading 1. __set($name, $value)Called when setting a value to an undefined or inaccessible property. 2. __get($name)Called when accessing an undefined or inaccessible property. 3. __isset($name)Called when using isset() or empty() on an undefined or inaccessible property. 4. __unset($name)Called when unset() is used on an undefined or inaccessible property
  • 64. class Person { private $data = []; // Store undefined properties // Handle setting undefined properties public function __set($name, $value) { echo "Setting '$name' to '$value'.n"; $this->data[$name] = $value; } // Handle getting undefined properties public function __get($name) { echo "Getting '$name'.n"; return $this->data[$name] ?? "Property '$name' not set."; } // Handle checking undefined properties public function __isset($name) { echo "Checking if '$name' is set.n"; return isset($this->data[$name]); }
  • 65. // Handle unsetting undefined properties public function __unset($name) { echo "Unsetting '$name'.n"; unset($this->data[$name]); } } $person = new Person(); $person->name = "John"; // __set is called echo $person->name . "n"; // __get is called echo isset($person->name) . "n"; // __isset is called unset($person->name); // __unset is calledecho $person->name . "n"; // __get is called Output: Setting 'name' to 'John’. Getting 'name’ John Checking if 'name' is set.1 Unsetting 'name’. Getting 'name’. Property 'name' not set.
  • 66. Inheritance in PHP • Inheritance allows a class to inherit properties and methods from another class, promoting code reuse. The class that is inherited from is called the parent class or base class, and the class that inherits is called the child class or derived class. • In PHP, inheritance is primarily single inheritance, but it can simulate other types through interfaces or traits. Here's an explanation of the types of inheritance:
  • 67. Single Inheritance A child class inherits from only one parent class. PHP does not support multiple inheritance directly to avoid ambiguity. class ParentClass { public function display() { echo "This is the parent class."; } } class ChildClass extends ParentClass { public function show() { echo "This is the child class."; } } $child = new ChildClass(); $child->display(); // Inherited from ParentClass $child->show(); // Defined in ChildClass
  • 68. 2. Multilevel Inheritance A class inherits from a child class, which in turn inherits from another parent class. This forms a chain of inheritance. class GrandParentClass { public function greet() { echo "Hello from the grandparent."; } } class ParentClass extends GrandParentClass { public function welcome() { echo "Welcome from the parent."; } } class ChildClass extends ParentClass { public function hello() { echo "Hello from the child."; } }
  • 69. $child = new ChildClass(); $child->greet(); // From GrandParentClass $child->welcome(); // From ParentClass $child->hello(); // From ChildClass
  • 70. 3. Hierarchical Inheritance Multiple child classes inherit from the same parent class. class ParentClass { public function display() { echo "This is the parent class."; } } class ChildClass1 extends ParentClass { public function show() { echo "This is the first child class."; } } class ChildClass2 extends ParentClass { public function exhibit() { echo "This is the second child class."; } }
  • 71. $child1 = new ChildClass1(); $child1->display(); $child1->show(); $child2 = new ChildClass2(); $child2->display(); $child2->exhibit();
  • 72. 4. Multiple Inheritance (via Traits) PHP does not support multiple inheritance directly but achieves it through traits, which allow a class to inherit behavior from multiple sources. trait Trait1 { public function method1() { echo "This is from Trait1."; } } trait Trait2 { public function method2() { echo "This is from Trait2."; } } class MyClass { use Trait1, Trait2; public function method3() { echo "This is from MyClass."; } }
  • 73. $obj = new MyClass(); $obj->method1(); // From Trait1 $obj->method2(); // From Trait2 $obj->method3(); // From MyClass
  • 74. Constructor • A constructor is a method used to initialize an object when it is created. • It is defined using the __construct() method. • It can accept parameters to pass initial values to the object. Syntax: class ClassName { public function __construct($param1, $param2) { // Initialization code } }
  • 75. Why is a Constructor Used? 1.Automatic Setup: A constructor saves you the trouble of setting up each object manually. 2.Consistency: It ensures every object starts with proper initial values or configurations. 3. Convenience: You can pass data to the constructor when creating the object, and it will use this data to set up the object.
  • 76. 1. Default Constructor A constructor with no parameters. Used to initialize default values for an object. <?phpclass Person { public function __construct() { echo "Default constructor calledn"; } } $obj = new Person(); // Output: Default constructor called?>
  • 77. 2. Parameterized Constructor A constructor that accepts parameters to initialize an object with specific values <? phpclass Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; echo "Name: $this->name, Age: $this->agen"; } } $obj = new Person("John", 25); // Output: Name: John, Age: 25?>
  • 78. 3. Copy ConstructorIn PHP • objects are copied by reference, so there isn't a direct implementation of a copy constructor like in some other languages. • However, you can manually create a method to copy properties of one object to another. <?phpclass Person { public $name; public function __construct($name) { $this->name = $name; } public function copy(Person $other) { $this->name = $other->name; } } $obj1 = new Person("Alice"); $obj2 = new Person("Bob"); $obj2->copy($obj1); echo $obj2->name; // Output: Alice?>
  • 79. Destructor • A destructor is a method that is automatically called when an object is no longer needed or the script ends. • It is defined using the __destruct() method. • Typically used to clean up resources like closing database connections or file handles. Syntax: class ClassName { public function __destruct() { // Cleanup code } }
  • 80. <?phpclass Person { public $name; public function __construct($name) { $this->name = $name; echo "Object created for $this->namen"; } public function __destruct() { echo "Object destroyed for $this->namen"; } } $obj = new Person("John");// Destructor is called automatically at the end of the script ?>
  • 81. SQL Commands SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index
  • 82. The MySQL CREATE DATABASE Statement The CREATE DATABASE statement is used to create a new SQL database. Syntax CREATE DATABASE databasename; The MySQL DROP DATABASE Statement The DROP DATABASE statement is used to drop an existing SQL database. Syntax DROP DATABASE databasename;
  • 83. The MySQL CREATE TABLE Statement The CREATE TABLE statement is used to create a new table in a database. Syntax CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... ); The MySQL DROP TABLE Statement The DROP TABLE statement is used to drop an existing table in a database. Syntax DROP TABLE table_name;
  • 84. MySQLALTER TABLE Statement  The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.  The ALTER TABLE statement is also used to add and drop various constraints on an existing table. ALTER TABLE - ADD Column To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype;
  • 85. The MySQL SELECT Statement The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set. Syntax SELECT column1, column2, ... FROM table_name; Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax: SELECT * FROM table_name;
  • 86. The MySQL INSERT INTO Statement The INSERT INTO statement is used to insert new records in a table. Syntax It is possible to write the INSERT INTO statement in two ways: 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); 2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows: INSERT INTO table_name VALUES (value1, value2, value3, ...);
  • 87. The MySQL UPDATE Statement The UPDATE statement is used to modify the existing records in a table. Syntax UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; The MySQL DELETE Statement The DELETE statement is used to delete existing records in a table. Syntax DELETE FROM table_name WHERE condition;
  • 89. UPDATE: <?php // Database connection $conn = mysqli_connect("localhost:3308", "root", "", "demo"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Update query $sql = "UPDATE student SET course=‘PHP and MYSQL', age=19 WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully."; } else { echo "Error updating record: " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>