0% found this document useful (0 votes)
2 views26 pages

Unit 4 function and class PHP and MySQL (1)

This document covers Unit 4 of a PHP and MySQL course, focusing on functions and classes, including user-defined functions and advanced OOP concepts. It explains the advantages of using functions, such as code reusability, ease of understanding, and debugging. Additionally, it discusses variable scope, recursive functions, and provides examples of creating and invoking functions, along with handling arguments and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views26 pages

Unit 4 function and class PHP and MySQL (1)

This document covers Unit 4 of a PHP and MySQL course, focusing on functions and classes, including user-defined functions and advanced OOP concepts. It explains the advantages of using functions, such as code reusability, ease of understanding, and debugging. Additionally, it discusses variable scope, recursive functions, and provides examples of creating and invoking functions, along with handling arguments and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

College:Vedanth BCA and Bcom College,Vijayapura

Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Unit 4
Functions and Classes: Creating User-Defined Functions -Creating Classes –Using Advanced OOP Concepts.
Working with Database MySQL and PHP, MYSQL and PHP Database Create, Read, Update and Delete
operations.

PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list and return
value. There are thousands of built-in functions in PHP.

PHP provides us with two major types of functions:


1. Built-in functions: PHP provides us with huge collection of built-in library functions. These functions are
already coded and stored in form of functions. To use those we just need to call them as per our requirement
like, var_dump, fopen(), print_r(), gettype() and so on.
2. User Defined Functions: Apart from the built-in functions, PHP allows us to create our own customized
functions called the user defined functions.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function,
you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of
the application because every logic is divided in the form of functions.

Function Syntax:
•Function declaration: ( With Parameters , Without Parameters )
function functionName($parameter1, $parameter2, ...)
{
// Function code
}
• $parameter1, $parameter2, etc., are optional and can be used to pass data to the function.Functions are defined
using the function keyword, followed by a function name and a pair of parentheses.

Function Naming Rules:


• Function names are case-insensitive. (Not case sensitive)
• They must start with a letter or underscore.
• They can contain letters, numbers, and underscores.

Creating User-Defined Functions


These user-defined functions are a neat way for you to create independent, reusable code “packages” that
perform specific tasks and can be maintained independently of the main program.

Packaging your code into functions has four important advantages:


● It reduces duplication within a program, by allowing you to extract commonly used routines into a single
component. This has the added benefit of making programs smaller, more efficient, and easier to read.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
● A function is created once but used many times, often from more than one program. If the function code
changes, the changes are implemented in one spot (the function definition) while the function invocations
remain untouched. This fact can significantly simplify code maintenance and upgrades, especially when
contrasted with the alternative: manually changing every occurrence of the earlier code wherever it occurs (and
possibly introducing new errors in the process).
● Debugging and testing a program becomes easier when the program is subdivided into functions, as it
becomes easier to trace the source of an error and correct it with minimal impact on the rest of the program.
● Functions encourage abstract thinking, because packaging program code into a function is nothing more or
less than understanding how a specific task may be encapsulated into a generic component. In this sense,
functions encourage the creation of more robust and extensible software designs.

Creating and Invoking Functions


There are three components to every function:
● Arguments, which serve as inputs to the function
● Return values, which are the outputs returned by the function
● The function body, which contains the processing code to turn inputs into outputs
Example:
one that doesn’t use either arguments or return values. Consider the following PHP script, which contains a
user-defined function to print the current day of the week.
<?php
// function definition
// print today's weekday name
function whatIsToday() {
echo "Today is " . date('l', mktime());
}
// function invocation
whatIsToday();
?>
 Function definitions begin with the function keyword, followed by the function name and a list of
arguments (optional) in parentheses. Curly braces then enclose the main body of the function, which can
contain any legal PHP code, including variable definitions, conditional tests, loops, and output
statements.
 Function names must begin with a letter or underscore character, optionally followed by more letters,
numbers, or underscore characters; punctuation characters and spaces are not allowed within function
names.
 In the preceding listing, the function is named whatIsToday() and its body contains a single statement,
which uses echo and date() to obtain and print the current weekday name. of course, defining a function
is only half the battle: the other half is using it. In PHP, invoking a function is as simple as calling it by
name (and passing it optional arguments, if needed). The main body of the script in the preceding listing
does just this: it invokes the function by name and then stands back to see the results.

Using Arguments and Return Values


Arguments are “placeholder” variables within a function definition; they’re replaced at run time by values
provided to the function from the main program. The processing code within the function then manipulates
these values to return the desired result. Since the input to the function will differ each time it is invoked, the
output will necessarily differ too.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
To illustrate, consider the following listing, which defines a function accepting two arguments and uses these
arguments to perform a geometric calculation:
<?php
// function definition
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width) {
$perimeter = 2 * ($length + $width);
echo "The perimeter of a rectangle of length $length
units and width $width units is: $perimeter units";
}
// function invocation
// with arguments
getPerimeter(4,2);
?>
The function in this listing performed a calculation and then printed the result directly to the output page.

Return Values
PHP, you can have a function explicitly return a value, like the result of a calculation, to the statement that
called it. This is accomplished by using a return statement inside the function, as in the next example:
<?php
// function definition
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width) {
$perimeter = 2 * ($length + $width);
return $perimeter;
}
// function invocation
// with arguments
echo 'The perimeter of a rectangle of length 4 units and width 2 units is: ' . getPerimeter(4,2) . ' units';
?>
You can return multiple values from a function, by placing them all in an array and returning the array.

Note: When PHP encounters a return statement inside a function, it halts processing of the function and
“returns” control to the main body of the program.

Setting Default Argument Values


It can assign default values to any or all of these arguments; these default values are used in the event the
function invocation is missing some arguments. Here’s an example, which generates an e-mail address from
supplied username and domain arguments; if the domain argument is missing, a default domain is automatically
assigned:
<?php
// function definition
// generate e-mail address from supplied values
function buildAddress($username, $domain = 'mydomain.info') {
return $username . '@' . $domain;
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
}
// function invocation
// without optional argument
// output: 'My e-mail address is [email protected]'
echo 'My e-mail address is ' . buildAddress('john');
// function invocation
// with optional argument
// output: 'My e-mail address is [email protected]'
echo 'My e-mail address is ' . buildAddress('jane', 'cooldomain.net');
?>
Notice that in the first instance, the function has been called with only a single argument, even though the
function definition requires two. However, since a default value is present for the second argument, the missing
argument is automatically replaced by said default value, and no errors are generated.

Note
If only some of your function’s arguments have default values assigned to them, place these arguments at the
end of the function’s argument list. This lets PHP correctly differentiate between missing arguments that don’t
have default values, and missing arguments that do.

Using Dynamic Argument Lists


A PHP function definition normally has a fixed argument list, where the number of arguments is known in
advance. However, PHP also lets you define functions with so-called variable-length argument lists, where the
number of arguments can change with each invocation of the function.
A good example of this is a function that accepts an arbitrary number of arguments, adds them up, and returns
the average . . . as illustrated in the following listing:
<?php
// function definition
// calculate average of supplied values
function calcAverage() {
$args = func_get_args();
$count = func_num_args();
$sum = array_sum($args);
$avg = $sum / $count;
return $avg;
}
// function invocation
// with 3 arguments
// output: 6
echo calcAverage(3,6,9);
// function invocation
// with 8 arguments
// output: 150
echo calcAverage(100,200,100,300,50,150,250,50);
?>
Notice that the calcAverage() function definition in the previous listing does not include a predefined argument
list; rather, the arguments passed to it are retrieved at run time using the func_num_args() and func_get_args()
functions. The func_num_ args() function returns the number of arguments passed to a function, while the func_
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
get_args() function returns the actual argument values, as an array. As illustrated in the preceding listing, both
functions come in very handy when dealing with functions that accept an arbitrary number of arguments.

Understanding Variable Scope


A key concept related to user-defined functions in PHP is variable scope: the extent of a variable’s visibility
within the space of a PHP program.

Local Variable
By default, variables used within a function are local—their impact is restricted to the function space alone, and
they cannot be viewed or manipulated from outside the function in which they exist. To illustrate this, consider
the following example:
<?php
// function definition
// change the value of $score
function changeScore() {
$score = 25;
}
// define a variable in the main program
// print its value
$score = 11;
echo 'Score is: ' . $score; // output: 11
// run the changeScore() function
changeScore();
// print $score again
echo 'Score is: ' . $score; // output: 11
?>
 Here, the variable $score is defined in the main program, and the changeScore() function contains code
to change the value of this variable. However, after running this function, the value of $score remains at
its original setting, because the changes made to $score within the changeScore() function remain
“local” to the function and do not reflect in the main program.
 This “bounding” of variables to within a function space is deliberate: it maintains a degree of separation
between the main program and its functions, and it reduces the chances of variables from the main
program affecting variables within a function. However, there are certainly occasions when it may be
necessary to “import” a variable from the main program into a function, or vice versa.

Global Variable
PHP offers the global keyword: when applied to a variable inside a function, this keyword turns the variable
into a global variable, making it visible both inside and outside the function.The next example illustrates the
difference between global and local scope more clearly:
<?php
// function definition
// change the value of $score
function changeScore() {
global $score;
$score = 25;
}
// define a variable in the main program
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
// print its value
$score = 11;
echo 'Score is: ' . $score; // output: 11
// run the changeScore() function
changeScore();
// print $score again
echo 'Score is: ' . $score; // output: 25
?>
In this revision of the previous listing, the global keyword used with the $score variable within the
changeScore() function changes the scope of the variable, increasing its scope to encompass the entire program.
As a result, changes made to the variable within the function will reflect in the main program (and vice versa).
The output of the script illustrates this fact clearly.

Using Recursive Functions


A recursive function is a function that calls itself repeatedly until a condition is satisfied. Such a function is
typically used to solve complex, iterative calculations, or to process deeply nested structures.
'tea',
'ten',
'tag',
'twentythree' => array(
array('twenty', 'three'),
array('vingt', 'trois', array(
'red' => 'baron',
'blue' => 'blood'
))
)
)
);
// count and print values in nested array
$ret = printValues($data);
echo $ret['total'] . ' value(s) found: ';
echo implode(', ', $ret['values']);
?>
The output of this example would be
12 value(s) found: orange, owl, one, tea, ten, tag, twenty, three, vingt, trois, baron, blood

 The core of this example is the printValues() function, which accepts an array as argument. It then loops
through this array using a foreach loop, adding each value it finds to an output array named $out. For
each such value found, it also increments a counter named $count by 1.
 In the event that any of the values encountered in this manner is itself an array, printValues() calls itself
recursively to process that child array (and any other child arrays found at deeper nesting levels). This
process continues until no further values are left to be processed.Because both $out and $count are
global variables, they maintain their values throughout this process.
 Once the function has completed its work, these two variables are packaged into a single associative
array, which is returned to the caller and printed to the output page.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Note: While recursive functions are often the quickest way to solve a complex calculation, they’re not the only
way: in most cases, you can accomplish the same thing, albeit less elegantly, by using one or more loops.

Calculating GCF and LCM


Here’s the code (gcf_lcm.php):
<?php
// function definition
// get GCF of two numbers
function getGCF($a, $b) {
if ($b == 0) {
return $a;
}
else {
return getGCF($b, $a % $b);
}
}
// function definition
// get LCM of two numbers using GCF
function getLCM($a, $b) {
return ($a * $b) / getGCF($a, $b);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Project 5-1: GCF and LCM</title>
</head>
<body>
<h2>Project 5-1: GCF and LCM</h2>
<?php
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
?>
<form method="post" action="gcf_lcm.php">
Enter two integers: <br />
<input type="text" name="num_1" size="3" />
<p>
<input type="text" name="num_2" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// if form submitted
// process form input
} else {
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
$num1 = (int)$_POST['num_1'];
$num2 = (int)$_POST['num_2'];
// calculate and print GCF and LCM
echo "You entered: $num1, $num2";
echo "<br />";
echo "The GCF of ($num1, $num2) is: " . getGCF($num1, $num2);
echo "<br />";
echo "The LCM of ($num1, $num2) is: " . getLCM($num1, $num2);
}
?>
</body>
</html>
This script generates a form for the user to enter two numbers (Figure 5-1). Once the form is submitted, the
numbers entered by the user are passed as arguments to the getGCF() and getLCM() functions, which,
respectively, calculate and return the GCF and LCM of the number pair to the caller. Figure 5-2 displays the
results of one such form submission.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)

Since this chapter is all about functions, it’s worthwhile spending a few minutes to dissect the getGCF() and
getLCM() functions.
The getGCF() function accepts two arguments and calculates the GCF value using the Euclidean algorithm.
Wikipedia’s description of this algorithm, at http://en.wikipedia .org/wiki/Euclidean_algorithm, states: “Given
two natural numbers a and b, not both equal to zero: check if b is zero; if yes, a is the GCD. If not, repeat the
process using, respectively, b, and the remainder after dividing a by b.” From this description, it should be clear
that the Euclidean algorithm can be expressed as a recursive function that calls itself repeatedly, feeding the
remainder of the previous division into the next one until the remainder becomes zero. If you look at getGCF(),
you’ll see that’s precisely what it does.
Once the GCF has been calculated, the LCM can be easily obtained using the relationship LCM (A,B) =
(A*B)/GCF(A,B). This relationship, and its derivation, may also be obtained from Wikipedia, at
http://en.wikipedia.org/wiki/Least_common_ multiple—and if you look inside the getLCM() function, you’ll
see this same calculation in action. You’ll notice also that getLCM() internally calls getGCF()—a fine example
of inter-function cooperation and an illustration of how functions can be used to break down large complex
tasks into smaller, more focused operations.

Creating Classes
PHP also allows you to group related functions together using a class. Classes are the fundamental construct
behind object-oriented programming (OOP), a programming paradigm that involves modeling program
behavior into “objects” and then using these objects as the basis for your applications.

Introducing Classes and Objects


 Class is a self-contained, independent collection of variables and functions, which work together to
perform one or more specific (and usually related) tasks. Variables within a class are called properties;
functions are called methods.
 Classes serve as templates for objects, which are specific instances of a class. Every object has
properties and methods corresponding to those of its parent class. Every object instance is completely
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
independent, with its own properties and methods, and can thus be manipulated independently of other
objects of the same class.
Example: an Automobile class that contain properties for color and make, and methods for acceleration,
braking, and turning. It’s possible to derive two independent objects from this Automobile class, one
representing a Ford and the other a Honda. Each of these objects would have methods for acceleration, braking,
and turning, as well as specific values for color and make. Each object instance could also be manipulated
independently: for example, you could change the Honda’s color without affecting the Ford, or call the Ford’s
acceleration method without any impact on the Honda.
Figure 5-3 illustrates the relationship between a class and its object instances visually.

Defining and Using Classes


 A class definition begins with the class keyword, which is followed by the class name and a pair of curly
braces. The complete class definition must be enclosed within these braces; in most cases, this definition
consists of property (variable) definitions followed by method (function) definitions.
 Once a class has been defined, objects can be created from the class with the new keyword. Class
methods and properties can directly be accessed through this object instance. sets the object’s properties
and invokes object methods (note the -> symbol used to connect objects to their properties or methods)
Class syntax:
class classname
{
var $variable_name; //data members/properties
var $variable_name;
function Method_name() //parameter_list/method member function
{
Body of method;
}
function Method_name() //parameter_list/method member function
{
Body of method;
}
}
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Object Syntax:
$object_name=new classname;

To see what a class definition looks like, review the following listing: it contains a definition for an Automobile
class, with two properties named $color and $make and methods named accelerate(), brake(), and turn():
<?php
// class definition
class Automobile {
// properties
public $color;
public $make;
// methods
public function accelerate() {
echo 'Accelerating...';
}
public function brake() {
echo 'Slowing down...';
}
public function turn() {
echo 'Turning...';
}
}
?>
which creates an instance of the Automobile class and assigns it to $car, and then sets the object’s properties and
invokes object methods (note the -> symbol used to connect objects to their properties or methods):
<?php
// instantiate object
$car = new Automobile;
// set object properties
$car->color = 'red';
$car->make = 'Ford Taurus';
// invoke object methods
$car->accelerate();
$car->turn();
?>

this keyword
To access or change a class method or property from within the class itself, it’s necessary to prefix the
corresponding method or property name with $this, which refers to “this” class.
consider this revision of the preceding example, which sets a class property named $speed and then modifies
this property from within the accelerate() and brake() functions:
<?php
// class definition
class Automobile {
// properties
public $color;
public $make;
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
public $speed = 55;
// methods
public function accelerate() {
$this->speed += 10;
echo 'Accelerating to ' . $this->speed . '...';
}
public function brake() {
$this->speed -= 10;
echo 'Slowing down to ' . $this->speed . '...';
}
public function turn() {
$this->brake();
echo 'Turning...';
$this->accelerate();
}
}
?>
And now, when you invoke these functions, you’ll see the effect of changes in $speed:
<?php
// instantiate object
$car = new Automobile;
// invoke methods
// output: 'Accelerating to 65...'
// 'Slowing down to 55...'
// 'Turning...'
// 'Accelerating to 65...'
$car->accelerate();
$car->turn();
?>

Using Advanced OOP Concepts


PHP’s object model also supports many more advanced features, giving developers a great deal of power and
flexibility in building OOP-driven applications. This section illustrates three such features: constructors and
destructors, extensibility, and visibility.

Using Constructors and Destructors


 PHP makes it possible to automatically execute code when a new instance of a class is created, using a
special class method called a constructor. You can also run code when a class instance ends using a so-
called destructor.
 Constructors and destructors can be implemented by defining functions named __construct() and
__destruct() within the class, and placing object (de)initialization code within them.
Here’s a simple example illustrating how this works:
<?php
// define class
class Machine {
// constructor
function __construct() {
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
echo "Starting up...\n";
}
// destructor
function __destruct() {
echo "Shutting down...\n";
}
}
// create an object
// output: "Starting up..."
$m = new Machine();
// then destroy it
// output: "Shutting down..."
unset($m);
?>

Extending Classes
Extensibility implies that a new class can be derived from an existing one, inheriting all the properties and
methods of the parent class and adding its own new properties and methods as needed. In PHP, extending a
class is as simple as attaching the extends keyword and the name of the class being extended to a class
definition.
<?php
class MyClass
{
public function hello()
{
echo "Hello World!";
}
}

class AnotherClass extends MyClass {


}

$obj = new AnotherClass();


$obj->hello();
?>
Output: Hello World!

Adjusting Visibility Settings


PHP allows you to exert even greater control over the visibility of object properties and methods. Three levels
of visibility exist, ranging from most visible to least visible; these correspond to the public, protected, and
private keywords.
 keyword public; this sets the corresponding class methods and properties to be “public” and allows a
caller to manipulate them directly from the main body of the program. This “public” visibility is the
default level of visibility for any class member (method or property) under PHP.
 you can explicitly mark a particular property or method as private or protected, depending on how much
control you want to cede over the object’s internals.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
 “Private” methods and properties are only visible within the class that defines them, “protected”
methods and properties are visible to both their defining class and any child (inherited) classes. attempts
to access these properties or methods outside their visible area typically produces a fatal error that stops
script execution.
Example:
<?php
Class Myclass
{
public $fname=”Ajay”;
var $lname;
private $marks=100;
protected $age=20;
function displaydata()
{
$this->lname=”Diwan”;
echo “$this->fname $this->lname”;
echo “marks=$this->marks ,age=$this->age”;
}
}
$obj=new myclass();
$obj->displaydata();
?>
Output:Ajay Diwan
Marks=100 age=20

Working with Database MySQL and PHP


What is Database?
❏ A database is an organized collection of related data.
❏ So nowadays, we use relational database management systems (RDBMS) to store and manage huge volume
of data. ❏ This is called relational database because all the data is stored into different tables and relations are
established using primary keys or other keys known as foreign keys.
❏ When creating databases and tables, you should come up with names (formally called identifiers) that are
clear, meaningful, and easy to type.
Also, identifiers
❏ Should only contain letters, numbers, and the underscore (no spaces)
❏ Should not be the same as an existing keyword (like an SQL term or a function name)
❏ Should be treated as case-sensitive
❏ Cannot be longer than 64 characters (approximately)
❏ Table cannot have two columns with the same name and a database cannot have two tables with the same
name.

RDBMS Terminology:
Before we proceed to explain MySQL database system, let's revise few definitions related to database.
Database: A database is a collection of tables, with related data.
Table: A table is collection of unnamed rows and named columns.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Column: One column (data element) contains data of one and the same kind, it is also called as attribute / field.
..…
Row: A row (= tuple, entry or record) is a group of fields data.
Redundancy: Storing same data multiple times, redundantly to make the system faster.
Primary Key: A primary key is unique. This cannot allow duplicate values.
Foreign Key: A foreign key is a key it acts as a primary key of another table and which creates link between
two tables. Compound Key: A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
MySQL Database:
❏ MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses.
❏ MySQL is released under an open-source license. So you have nothing to pay to use it.
❏ MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most
expensive and powerful database packages.
❏ MySQL uses a standard form of the well-known SQL data language.
❏ MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA,
etc.
❏ MySQL works very quickly and works well even with large data sets.
❏ MySQL is very friendly to PHP, the most appreciated language for web development.
PHP supports more than fifteen different database engines, including Microsoft SQL Server, IBM DB2,
PostgreSQL, MySQL, and Oracle. Until PHP 5, this support was offered through native database extensions

MySQL Data types:


Each column in a database table is required to have a name and a data type. A Programmer must decide what
type of data that will be stored inside each column when creating a table.
In MySQL there are three main data types: number, text and date.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Understanding SQL Statements
Structured Query Language, or SQL, is the standard language used to communicate with a database, add or
change records and user privileges, and perform queries. The language, which became an ANSI standard in
1989, is currently used by almost all of today’s commercial RDBMSs.

SQL statements fall into one of three categories:


● Data Definition Language (DDL) :DDL consists of statements that define the structure and relationships of
a database and its tables. Typically, these statements are used to create, delete, and modify databases and tables;
specify field names and types; and set indexes.
CREATE - to create a database and its objects like (table, index, views, store procedure, function, and triggers)
ALTER - alters the structure of the existing database.
DROP – delete column data and entire data with structure.
TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed

● Data Manipulation Language (DML):DML statements are related to altering and extracting data from a
database. These statements are used to add records to, and delete records from, a database; perform queries;
retrieve table records matching one or more user-specified criteria; and join tables together using their common
fields.
SELECT - retrieve data from a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - Delete all records from a database table

● Data Control Language (DCL): DCL statements are used to define access levels and security privileges for
a database. You would use these statements to grant or deny user privileges; assign roles; change passwords;
view permissions; and create rule sets to protect access to data.
GRANT - allow users access privileges to the database
REVOKE - withdraw user’s access privileges given by using the GRANT command
Creating the Database
Since all tables are stored in a database, the first step is to create one, using the CREATE DATABASE
statement:
mysql> CREATE DATABASE music;
Query OK, 1 row affected (0.05 sec)
Next, select this newly minted database as the default for all future commands with the USE statement:
mysql> USE music;
Database changed

Using PHP’s SQLite Extension


 SQLite is a fast, efficient database system that offers a viable alternative to MySQL, especially for small- to
medium-sized applications. However, unlike MySQL, which contains a large number of interrelated
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
components, SQLite is fully self-contained in a single library file. It’s also significantly smaller in size than
MySQL—the commandline version of SQLite weighs in at under 200KB—and supports all the standard
SQL commands you’re used to.
 MySQL and SQLite also differ in their licensing policies: unlike MySQL, SQLite source code is completely
public-domain, which means that developers can use and distribute it however they choose, in both
commercial and noncommercial products.
 SQLite’s small size belies its capabilities, however. It supports databases up to two terabytes in size and can
actually produce better performance than MySQL in certain situations. Part of this is for architectural
reasons: SQLite reads and writes records directly from and to database files on disk and so incurs less
performance overhead than MySQL, which operates a client-server architecture that may be affected by
network-level variables.
 To begin, create a new SQLite database named todo.db, and add an empty table to hold task descriptions
and dates:
shell> sqlite todo.db

Handling Errors SQLite


Both the query() and queryExec() methods return false if an error occurs during query preparation or execution.
It’s easy to check the return value of these methods and retrieve the code corresponding to the error by calling
the SQLiteDatabase object’s lastError() method. Unfortunately, this error code isn’t very useful by itself; so, for
a textual description of what went wrong, wrap the call to lastError() in the sqlite_ error_string() function, as
most of the preceding examples do.

There are three ways of working with MySQl and PHP


1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO
1.MySQLi (object-oriented)
PHP also includes a custom MySQL extension named MySQL Improved (MySQLi).
1. In order to begin communication with the MySQL database server, you first need to open a connection to
the server. All communication between PHP and the database server takes place through this connection. In
order to initialize this connection, initialize an instance of the MySQLi class and pass the object constructor
four arguments: the host name of the MySQL server to connect to, a valid username and password to gain
access to it, and the name of the database to use.
Assuming the connection attempt is successful, this object instance represents the database connection for
all future operations and exposes methods for querying, fetching, and processing result sets. If the
connection attempt is unsuccessful, the object instance will become false; an error message explaining the
reason for failure can now be obtained by calling the mysqli_connect_error() function.
Note: If the database server and the Web server are both running on the same physical machine, you can use
localhost as the server name.
2. The next step is to create and execute the SQL query. This is accomplished by calling the MySQLi object’s
query() method and passing it the query to be executed. If the query was unsuccessful, the method returns
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
Boolean false, and an error message explaining the cause of failure is stored in the MySQLi object’s 'error'
property.
3. If, on the other hand, the query is successful and returns one or more records, the return value of the query()
method is another object, this one an instance of the MySQLi_ Result class. This object represents the result
set returned by the query, and it exposes various methods for processing the individual records in the result
set. One such method is the fetch_array() method. Each time fetch_array() is invoked, it returns the next
record in the result set as an array.
This makes the fetch_array() method very suitable for use in a while or for loop. The loop counter
determines how many times the loop should run; this value is obtained from the MySQLi_Result object’s
'num_rows' property, which stores the number of rows returned by the query. Individual fields from the
record can be accessed as array elements, using either the field index or the field name.
4. Each result set returned after a query occupies some amount of memory. Thus, once the result set has been
processed, it’s a good idea to destroy the MySQLi_Result object, and free up the used memory, by calling
the object’s close() method. And once you’ve completed working with the database, it’s also a good idea to
destroy the main MySQLi object in a similar manner, by calling its close() method.
Syntax: <?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output: Connected Successfully
Explanation: We can create an instance of the mysqli class providing all the necessary details required to
establish the connection such as host, username,password etc. If the instance is created successfully then the
connection is successful otherwise there is some error in establishing connection.

Handling Errors MySQLi


If your database code doesn’t work as expected, don’t worry—the MySQLi extension comes with a bunch
of functions that can tell you why. You’ve already seen these in action at various places in previous listings,
but here’s a complete list:
● The MySQLi object’s 'error' property holds the last error message generated by the database server.
● The MySQLi object’s 'errno' property holds the last error code returned by the database server.
● The mysqli_connect_error() function returns the error message generated by the last (failed) connection
attempt.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
● The mysqli_connect_errno() function returns the error code generated by the last (failed) connection
attempt.

2.PDO(PHP Data Object)


the PDO extension in greater detail, providing information on how it can be used to connect to different
database systems, perform queries, process result sets, and handle connection or query errors. Most of the
examples assume a MySQL database system; however, as you’ll see, PDO-based programs require minimal
modification to work with other database systems, including SQLite.
using PDO to get data from a database involves steps
1. The first step is to initialize an instance of the PDO class and pass the object constructor three
arguments: a Data Source Name (DSN) string indicating the type of database to connect to as well as
other database-specific options, a valid database username, and the corresponding password. The DSN
string varies from database to database; you can typically obtain the exact format for this string from the
database’s documentation. If the connection attempt is unsuccessful, an exception will be raised; this
exception can be caught and handled using PHP’s exception-handling mechanism.

2. Assuming a successful connection, the next step is to formulate an SQL query and execute it using
PDO’s query() method. The return value of this method is a resultset, represented by a PDOStatement
object. The contents of the resultset can be processed using the object’s fetch() method, which returns
the next record in the resultset as an array (both associative and indexed). Individual fields from the
record can be accessed as array elements in a loop, using either the field index or the field name. The
PDOStatement object’s fetch() method accepts an additional modifier, which controls how result set
records are fetched.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)

Handling Errors PDO


Connection Errors
If PDO is unable to connect to the named database using the supplied DSN, username, and password, it
automatically generates a PDOException. This exception can be trapped using PHP’s standard exception-
handling mechanism and an error message explaining the cause of error can be retrieved from the exception
object.
Query Execution Errors
If an error occurs during query preparation or execution, PDO provides information on the error via its
errorInfo() method. This method returns an array containing three elements: the SQL error code, a database
error code, and a human-readable error message (also generated by the underlying database). It’s easy to process
this array and print the appropriate elements from it within the error-handling section of your script.

Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Output:Connected Sucussfully

Explanation:The exception class in PDO is used to handle any problems that may occur in our database
queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the
first catch(){ } block.

3. MySQLi procedural
There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP script
as described below.
Syntax: <?php
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output: Connection Succussfully

Explanation: In MySQLi procedural approach instead of creating an instance we can use the mysqli_connect()
function available in PHP to establish a connection. This function takes the information as arguments such as
host,username , password , database name etc. This function returns MySQL link identifier on successful
connection or FALSE when failed to establish a connection.

Run SQL Query


$conn->Query (SQL query) or $conn->prepare(SQL query)

Closing a Connection
When we establish a connection to MySQL database from a PHP script , we should also disconnect or close the
connection when our work is finished. Here we have described the syntax of closing the connection to a
MySQL database in all 3 methods described above. We have assumed that the reference to the connection is
stored in $conn variable.

Using MySQLi object oriented procedure


Syntax: $conn->close();

Using MySQLi procedural procedure


Syntax :mysqli_close($conn);

Using PDO procedure


Syntax: $conn = null;

Creating Database using MySQL and PHP


The CREATE DATABASE statement is used to create a database in MySQL.
<?php
$servername = "localhost";
$username = "username";
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Read data from Database using PHP


As we know Database is a collection of tables that stores data in it.To retrieve or fetch data from My SQL
database it is simple to do it using MySQL ” Select ” query in PHP .Here in this blog post we will be going to
see how to fetch data and to display it in front end.

MySQL Select Query:


SELECT column_name(s)
FROM table_name

PHP:
$query = mysql_query("select * from tablename", $connection);
For this you must have a database in MySQL . Here, we have a database named “company” which consists of a
table named “employee” with 5 fields in it. Next we have created a PHP page named “updatephp.php” where
following steps will be going to perform:
We first establish connection with server .
$connection = mysql_connect("localhost", "root", "");
Selects database.
$db = mysql_select_db("company", $connection);
Executes MySQL select query.
$query = mysql_query("select * from employee", $connection);
Display fetched data
<span>Name:</span> <?php echo $row1['employee_name']; ?>
<span>E-mail:</span> <?php echo $row1['employee_email']; ?>
<span>Contact No:</span> <?php echo $row1['employee_contact']; ?>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
<span>Address:</span> <?php echo $row1['employee_address']; ?>
Closing connection with server.
mysql_close($connection);

Update data using php


Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function
mysql_query. Below is a simple example to update records into employee table. To update a record in any table
it is required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
Example
Try out following example to understand update operation. You need to provide an employee ID to update an
employee salary.
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE emp_id = $emp_id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";

mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border =" 0" cellspacing = "1"
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
cellpadding = "2">
</tr>
<tr>
<td width = "100">Employee Salary</td>
<td><input name = "emp_salary" type = "text"
id = "emp_salary"></td>
</tr>
<tr>
<td width = "100">Employee ID</td>
<td><input name = "emp_id" type = "text"
id = "emp_id"></td>
<tr>
<td width = "100"> </td>
<td> </td>
</tr>
<tr>
<td width = "100"> </td>
<td>
<input name = "update" type = "submit"
id = "update" value = "Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

Deleting Data from MySQL Database


Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function
mysql_query. Below is a simple example to delete records into employee table. To delete a record in any table it
is required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
Example
Try out following example to understand delete operation. You need to provide an employee ID to delete an
employee record from employee table.
<html>
<head>
<title>Delete a Record from MySQL Database</title>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
</head>
<body>
<?php
if(isset($_POST['delete'])) {
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
$sql = "DELETE FROM employee WHERE emp_id = $emp_id" ; mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border = "0" cellspacing = "1"cellpadding = "2">
<tr>
<td width = "100">Employee ID</td>
<td><input name = "emp_id" type = "text"
id = "emp_id"></td>
</tr>
<tr>
<td width = "100"> </td>
<td> </td>
</tr>
<tr>
<td width = "100"> </td>
<td>
<input name = "delete" type = "submit"
id = "delete" value = "Delete">
</td>
</tr>
</table>
</form>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 4)
<?php
}
?>
</body>
</html>

Assignment Questions:
2 Marks Question
1.Define Function name PHP?
2.How do you pass arguments by reference in PHP functions?
3.List the statements that are used to connect PHP with MySQL With example.
4.What is class and object?
5.what is the significant of return Statement?
6.Differentiat between local and Global Variable.
7.what is DDL?
8.What is SQLite?
9.What is meant by server side Scripting?
10.what is PDO and MYSQLi?
11.What is User Defined Function?
12.what is MySQL?
13.What is Recursion function.
14.What is this keyword?

5 Marks Question
1.How do you create and invoke user defined functions in PHP?
2. Develop a PHP program to demonstrate constructors and destructors.
3. Write a PHP program that accepts two numbers using a web form and calculates greatest common divisor
(GCD) and least common multiple (LCM) of entered numbers.(Use recursive function).
4.define the terms class and object and illustrate with example?
5.Explain __Construct() and __destruct() methods.
6. Develop a PHP code to read the values entered into the form using the MySQL database.
7.Difference between MySQLi and MySQLite.
8.Difference between MySQLi and PDO.
6.Explain default argument values and dynamic argument values.
7.Explain PDO and MySQLi.
8.Explain Create,Read,Update and delete data from Mysql

You might also like