Unit 4 function and class PHP and MySQL (1)
Unit 4 function and class PHP and MySQL (1)
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.
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.
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.
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.
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.
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.
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.
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();
?>
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!";
}
}
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
● 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
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)
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.
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.
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);
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>
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