CH 5

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 121

Chapter Five

Server Side Scripting


By
Tesfahun
part I
Outline
Basic PHP Syntax

Variables in PHP

PHP Output Statements

 Conditional and Loop Statements

Arrays and Functions in PHP

Form Processing using PHP


what is PHP?
 PHP is an acronym for Hypertext Preprocessor"

PHP is a widely-used, open source scripting language

It is executed on the server

It is used to manage dynamic content, databases,

session tracking
why we learn PHP
 PHP runs on various platforms (Windows, Linux,

Unix, Mac OS X, etc.)

PHP is compatible with almost all servers used today


(Apache, IIS, etc.)

PHP supports a wide range of databases

PHP is easy to learn and runs efficiently on the


server side
What Can PHP Do?
It generate dynamic page content

It able create, open, read, write, delete, and close files on
the server

It is able to collect data from the form

Its able to send and receive cookies

Its able to add, delete, modify data in your database

To control user-access

To encrypt data


Basic PHP Syntax
 A PHP script can be placed anywhere in the
document.

A PHP script starts with <?php and ends with ?>:

file extension for PHP files is ".php".

<?php
// PHP code goes here
?>
Output Variables in PHP
The PHP echo statement is often used to output data to the
screen.

The print statement can be used with or without


parentheses: print or print().
<?php
echo “well came to study php“;

print "Hello world!<br>";
?>
example
<?php

echo "Hello World!";

?>
PHP comments
<?php
// This is a single-line comment

# This is also a single-line comment


/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
variables in PHP
 in PHP, a variable starts with the $ sign, followed by the
name of the variable

A variable name must start with a letter or the underscore


character

A variable name cannot start with a number

A variable name can only contain alpha-numeric characters


and underscores (A-z, 0-9, and _ )

Variable names are case-sensitive ($age and $AGE are two


different variables)
example
<?php
$name = "Hello world!";
$-a = 5;
$y = 10.5;
?>
PHp operator
 Arithmetic operators

Assignment operators

Comparison operators

Increment/Decrement operators

Logical operators

String operators

Array operators

Conditional assignment operators


Conditional assignment operators
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
PHP Conditional Statements
 PHP - The if Statement

The if statement executes some code if one


condition is true.

if (condition)

{
  code to be executed if condition is true;
}
example
<?php
$x = 5;

if ($x < "10")


{

echo "well came!";

?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is
true and another code if that condition is false.

Syntax

if (condition) {

code to be executed if condition is true;

} else {

code to be executed if condition is false;

}
example
<?php
$x = 5;
if ($x < "10") {
echo “the number is less than 10!";
}
else {
echo “the number is less than 5!";
}
?>
The PHP switch Statement
 Use the switch statement to select one of many blocks of code
to be executed.

 Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from all labels;
}
example
 <?php
$color = “yellow";
switch ($color) {
  case “pink":
    echo "Your favorite color is pink!";
    break;
  case "blue":
    echo "Your favorite color is blue!";
    break;
   default:
    echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
 In PHP, we have the following loop types:

while - loops through a block of code as long as the


specified condition is true

do...while - loops through a block of code once, and then


repeats the loop as long as the specified condition is true

for - loops through a block of code a specified number of


times

foreach - loops through a block of code for each element


in an array
while Loop
The while loop executes a block of code as long as
the specified condition is true.

Syntax

while (condition) {

code to be executed;

}
example
<?php
$num=1;

while($num<=5)

echo $num;

$num++;

?>
 The PHP do...while Loop

The do...while loop will always execute the block of code


once, it will then check the condition, and repeat the loop
while the specified condition is true.
Syntax

do {

code to be executed;

} while (condition is true);


example
<?php
$num=1;
do{
echo $num;
$num++;
}
while($num<=6)
?>
The PHP for Loop
The for loop is used when you know in advance how
many times the script should run.

Syntax

for (init counter; test counter; increment counter)

code to be executed for each iteration;

}
example
 <?php
for ($x = 0; $x <= 10; $x++) {
  echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used
to loop through each key/value pair in an array.

Syntax

foreach ($array as $value) {

code to be executed;

}
 <?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
  echo "$value <br>";
}
?>
PHP Arrays
 An array stores multiple values in one single
variable

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";

?>
types of array
 indexed

Associative

PHP - Two-dimensional Arrays


PHP - Multidimensional Arrays
A multidimensional array is an array containing one
or more arrays.

PHP supports multidimensional arrays that are


two, three, four, five, or more levels deep.
However, arrays more than three levels deep are
hard to manage for most people
example
$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

?>
PHP function
Syntax
function functionName()
{
  code to be executed;
}
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
PHP Form Processing
 Controls used in forms: Form processing contains
a set of controls through which the client and
server can communicate and share information.

All the form controls is designed by using the


input tag based on the type attribute of the tag.
cont..
 PHP methods and arrays used in form processing are:

$_GET[]: It is used the retrieve the information from the


form control through the parameters sent in the URL. It
takes the attribute given in the url as the parameter.

$_POST[]: It is used the retrieve the information from


the form control through the HTTP POST method. IT
takes name attribute of corresponding form control as the
parameter.
cont…
 isset(): This function is used to determine
whether the variable or a form control is having a
value or not.

$_REQUEST[]: It is used to retrieve an


information while using a database.
PHP File Upload
Database are the common means of storing data But
data can be store in Word documents, spreadsheets, image
files, and so on.

Databases generally require a special query language to


retrieve information, whereas files are ‘flat’ and usually
appear as a stream of text.

Since PHP is a server side programming language, it allows


you to work with files and directories stored on the web
server.
Working with Files in PHP
 In PHP there are some built-in wrapper functions
that helps to perform fill operation.

Most often when working with files you’ll read


from or write to them.

 To perform (r and w) operation firs the file


should be open or created

Finally close the file when you have finished.


cont…
 To work with a file you first need to open the file.

 The PHP fopen() function is used to open a file.

The basic syntax of this function can be given with

fopen(filename, mode)

It requires two arguments.


The first parameter of fopen() contains the name of the file to be
opened

second parameter specifies in which mode the file should be


opened(r,w,a…).
Example 1
<?php
$myfile = fopen( “test.txt" “r” , ) or
die("Unable to open file!");
// some cod….
?>
The name of the specifies in which mode
file the file should be
opened.

Set By:-Tesfahun N. 40
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the
string into file.
example
<?php

$file = fopen("f.txt", "w" );

fwrite( $file, “ well came to fill ...\n" );

fclose( $file );

?>
FILE_EXISTS() FUNCTION
 If you try to open a file that doesn't exist, PHP will
generate a warning message.
To avoid these error messages you should always
implement PHP file_exists() function.
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file))
{ // Attempt to open the file
$handle = fopen($file, "r");
}
else
{ echo "ERROR: File does not exist."; }
?>
PHP Close File - fclose()
 The fclose() function is used to close an open file.

It's a good programming practice to close all files after


you have finished with them.

The fclose() requires the name of the file (or a variable


that holds the filename) we want to close:
<?php
$myfile = fopen(“test.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Reading from Files with PHP fread() Function
The fread() function used to reads from an open file.
This function has two parameter
The first parameter name of the file to be read
second parameter specifies the maximum number of bytes to
read.
Syntax : fread(file, length in bytes)

The following PHP code reads the “test.txt" file to the


end:
<?php
$myfile = fopen(“test.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize(“test.txt"));
?>
the name of the file
Set maximum
By:-Tesfahun N. number of bytes to read. 44
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the “test.txt" file line by line, until end-of-file is
reached:
Example
<?php
$myfile = fopen(“test.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile))
{
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
Example
<?php
$myfile = fopen(“test.txt", "r") or
die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile))
{
  echo fgetc($myfile);
}
fclose($myfile);
?>
PHP Write file append
Appending a File:- is a process that involves adding new data
elements to an existing file

<?php

$fp = fopen('f.txt', 'a');//opens file in append mode

fwrite($fp, ' this is additional text ');

fwrite($fp, 'appending data');

fclose($fp);

echo "File appended successfully";

?>
File Attributes
File Size:-The function filesize() retrieves the
size of the file in bytes.
EXAMPLE
<?php
$f = "C:\Windows\win.ini";
$size = filesize($f);
echo $f . " is " . $size . " bytes.";
?>
When executed, the example code displays:
C:\Windows\win.ini is 92 bytes.

Set By:-Tesfahun N. 48
File History
To determine when a file was
 last accessed=> fileatime()
 modified=>filemtime(),
Changed =>filectime().,
<?php
$dateFormat = "D d M Y g:i A";
$f = "C:\Windows\win.ini";
$atime = fileatime($f);
$mtime = filemtime($f);
$ctime = filectime($f);
echo $f . " was accessed on " . date($dateFormat, $atime) . ".<br>";
echo $f . " was modified on " . date($dateFormat, $mtime) . ".<br>";
echo $f . " was changed on " . date($dateFormat, $ctime) . ".";
?>

Set By:-Tesfahun N. 49
File Permissions
Before working with a file you may want to check whether it is
readable or writeable to the process.

For this you’ll use the functions is_readable() and is_writeable():

<?php

$f = "f.txt";

echo $f .(is_readable($f)?"is":"is not").“ readable.<br>";

echo $f .(is_writable($f)?"is":"is not") . " writeable.";

?>

Set By:-Tesfahun N. 50
Working with CSV Files

 The fputcsv() function formats a line as CSV and writes


it to an open file.
<?php
$f = fopen("stud.csv", “r");
$newFields = array(array("Tom", "Jones", 36, "Accountant"),
array("Brenda", "Collins", 34, "Engineer"));
foreach($newFields as $fields)
{ fputcsv($f, $fields);
}
fclose($f);// The file must have been opened by fopen() or fsockopen().
?>

Set By:-Tesfahun N. 51
Reading of csv files
<?php
$f="stud.csv";
$fi = fopen($f, "r");
while ($record = fgetcsv($fi))
{
foreach($record as $field)
{
echo $field . "<br>";
}
}
fclose($f);
?>

Set By:-Tesfahun N. 52
Directories
The directory functions allow you to retrieve
information about directories and their contents.

basename():- Function returns the filename .

dirname() :-Function is essentially to providing the


directory component of path.

extension():- used to return the file extension

Set By:-Tesfahun N. 53
Example
<?php
$pathinfo= pathinfo("C:/xampp/htdocs/ip/f.txt");

echo "Dir name: $pathinfo[dirname]<br />\n";


echo "Base name: $pathinfo[basename] <br />\n";
echo "Extension: $pathinfo[extension] <br />\n";
?>
Output

Set By:-Tesfahun N. 54
Part II
.....
Objective
PHP Cookies and Session

Database Programming using PHP


 Overview on MySQL database

 Creating Database Connection in PHP

 Sending Query to MySQL Database using PHP

 Processing Query Result.


PHP File Input-Output
 PHP Date and Time
PHP Mathematical Functions
PHP OOP
PHP Cookies and Session
What is Cookie?

A cookie is a small file with the maximum size of 4KB that


the web server stores on the client computer

Once a cookie has been set, all page requests that follow
return the cookie name and value.

A cookie can only be read from the domain that it has been
issued from.
Creating Cookies
Let’s now look at the basic syntax used to create a cookie.

<?php

setcookie(cookie_name, cookie_value, [expiry_time],


[cookie_path], [domain], [secure], [httponly]);

?>
Cont..
 Php“setcookie” is the PHP function used to create the cookie.

“cookie_name” is the name of the cookie that the server will use
when retrieving its value from the $_COOKIE array variable. It’s
mandatory.

“cookie_value” is the value of the cookie and its mandatory

“[expiry_time]” is optional; it can be used to set the expiry time

“[cookie_path]” is optional; it can be used to set the cookie path on


the server.
Cont..
 “[domain]” is optional, it can be used to define the
cookie access hierarchy i.e. www.cookiedomain.com

“[secure]” is optional, the default is false. It is used to


determine whether the cookie is sent via https if it is
set to true or http if it is set to false.

“[Httponly]” is optional. If it is set to true, then only


client side scripting languages i.e. JavaScript cannot
access them.
Retrieving the Cookie value
Create another file named “cookies_read.php” with the
following code.
<?php
print_r($_COOKIE); //output the contents of the cookie
array variable
?>
Output:
Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611
[user_name] => Guru99 )
Delete Cookies
If you want to destroy a cookie before its expiry time, then
you set the expiry time to a time that has already passed.

Create a new filed named cookie_destroy.php with the


following code

<?php
setcookie("user_name", "Guru99", time() - 360,'/');
?>
What is a Session?
A session is a global variable stored on the server.

Each session is assigned a unique id which is used to retrieve


stored values.

Whenever a session is created, a cookie containing the unique


session id is stored on the user’s computer and returned with
every request to the server.

 If the client browser does not support cookies, the unique php
session id is displayed in the URL
Cont..
Sessions have the capacity to store relatively larger than
cookies.

The session values are automatically deleted when the browser


is closed.

to is possible store the values permanently in the database

Just like the $_COOKIE array variable, session variables are


stored in the $_SESSION array variable.

Just like cookies, the session must be started before any


HTML tags.
Why and when to use Sessions?
You want to store important information such as the user id
more securely on the server where malicious users cannot
temper with them.

You want to pass values from one page to another.

You want the alternative to cookies on browsers that do not


support cookies.

You want to store global variables in an efficient and more


secure way compared to passing them in the URL
Creating a Session
In order to create a session, you must first call the PHP
session_start function and then store your values in the
$_SESSION array variable.

Let’s suppose we want to know the number of times that a


page has been loaded, we can use a session to do that.

The code below shows how to create and retrieve values


from sessions
Cont..
<?php
session_start(); //start the PHP_session function
if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{ $_SESSION['page_count'] = 1;}
echo 'You are visitor number ' . $_SESSION['page_count'];
?>
Destroying Session Variables
The session_destroy() function is used to destroy the
whole Php session variables.

If you want to destroy only a session single item, you use
the unset() function.

The code below illustrates how to use both methods.


<?php
session_destroy(); //destroy entire session
?>
PHP MySQL Database
 With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

The data in a MySQL database are stored in tables.

A table is a collection of related data, and it consists of

columns and rows


What is MySQL?
MySQL is a database system used on the web

MySQL is a database system that runs on a server

MySQL is ideal for both small and large applications

MySQL is very fast, reliable, and easy to use

MySQL uses standard SQL

MySQL compiles on a number of platforms

MySQL is free to download and use


Cont..
 The ways of working with PHP and MySQL:

1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO
Steps to access MySQL database from PHP page

1. Create connection
2. Select a database to use
3. Send query to the database
4. Retrieve the result of the query
5. Close the connection
Create Connection to MySQL server

 Before we can access data in the MySQL


database, we need to be able to connect to the
server:

The way of connection to the server and Databse

1. MySQLi Object-Oriented
2. MySQLi Procedural
3. PHP Data Objects (PDO)
MySQLi Object-Oriented
<?php
$servername = "localhost";
$un = "root";
$pass = "";
// Create connection
$conn = new mysqli($servername, $un, $pass);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$sn = "localhost";
$un = "root";
$pas = "";
// Create connection
$conn = mysqli_connect($sn, $un, $pas);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully by using pros";
?>
Example (PDO)
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set 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();
}
?>
Closing a connection Using PHP Script

 You can disconnect from MySQL database anytime using


another PHP function takes a single parameter which is a
connection returned by mysql_connect() function.

Syntax:
mysql_close(resource $link_identifier);
 If a resource is not specified then last opened database is
closed.
 This function returns true if it closes connection
successfully otherwise it returns false.
Clothing connection
<?php
$conn = new mysqli("localhost",“un",“pas“)
if ($mysqli -> connect_error)

{
  echo "Failed to connect to MySQL: " . $mysqli ->
connect_error;
  exit();
}
$conn -> close();
?>
Creating Database Connection in PHP OOP

• The CREATE DATABASE statement is used to create a database


in MySQL.
// Create database
$sql = "CREATE DATABASE Bit";
if ($conn->query($sql) === TRUE)
{
  echo "Database created successfully";
} else {
  echo "Error creating database: " . $conn->error;
}
Example (MySQLi Procedural)
// Create database
$sql = "CREATE DATABASE Bit";
if (mysqli_query($conn, $sql))
{
  echo "Database created successfully";

else 
{
  echo "Error creating database: " .
mysqli_error($conn);
}
Drop Database using PHP Script
Note:- While deleting a database using PHP script, it does not
prompt you for any confirmation. So be careful while deleting a
MySql database.

Syntax
$sql = 'DROP DATABASE Bit’;
$qury = $mysqli->query ($conn, $sql );
if(! $qury )
{
die('Could not delete database: ' . mysqli_error());
}
81
Selecting MySQL Database Using PHP Script

 Once you get connection with MySQL server, it is required


to select a particular database to work with.
 This is because there may be more than one database
available with MySQL Server.
 PHP provides function mysql_select_db to select a database.

 It returns TRUE on success or FALSE on failure.

82
Cont..
Syntax:
mysql_select_db(db_name, connection);  
Where
 db_name:-Required - MySQL Database name to be
selected
 Connection:-Optional - if not specified then last opened
connection by mysql_connect will be used.
Example

<?php
include connection.php’;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully’;
mysqli_select_db( ‘Bit’ );//data base is selected
84
mysqli_close($conn);
?>
Creating table
Create a MySQL Table Using MySQLi
and PDO

The CREATE TABLE statement is used


to create a table in MySQL
Example (MySQLi Object-oriented)
// sql to create table
$sql = "CREATE TABLE stud (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50) )";

if ($conn->query($sql) === TRUE)


{
  echo "Table Bit created successfully";
}
 else {
  echo "Error creating table: " . $conn->error;
}
Example (MySQLi Procedural)
/ sql to create table
$sql = "CREATE TABLE Bit (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50), )";

if (mysqli_query($conn, $sql)) {
  echo "Table Bit created successfully";

else 
{
  echo "Error creating table: " . mysqli_error($conn);
}
dropping table (reading assignment )

Drop table stud


PHP MySQL Insert Data
• After a database and a table have been created, we can start
adding data in them.
• Here are some syntax rules to follow:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
Example (MySQLi Object-oriented)
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO stud (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
Example (MySQLi Procedural)
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if(!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Insert the data from HTML form
In real application, all the values will be taken using HTML form
and then those values will be captured using PHP script and finally
they will be inserted into MySql tables.

<form action="" method="POST">

Name <input type="text" name="name">

age <input type="text" name="age">

<input type="submit" name="submit">

</form>
Cont..
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = “Bit";
$con = mysqli_connect($server, $username, $password);
if(!$con){
echo "Error : ".mysqli_error();
return;
}
$db = mysqli_select_db($database,$con);
if(!$db)
{echo "Error : ".mysqli_error();
return;}
?>
Cont.
<?php

if(isset($_POST['submit']))

$name = $_POST["name"];

$age = $_POST["age"];

mysqli_query("insert into employee (name,age) value


('$name','$age') ")or die(mysql_error());

?>
Getting Data From MySql Database
 Data can be fetched from MySQL tables by executing SQL SELECT statement through

PHP function mysql_query().

 mysql_query() returns a result set of the query if the SQL statement is SELECT

 mysql_num_rows($result) : returns the number of rows found by a query

 mysql_fetch_row($result): returns a row as an array containing each field in the

row. It returns false when it reaches the end

 mysql_fetch_array($result): returns a row as an indexed array(numerical array)

just like mysql_fetch_row() and an associative array, with the names of the fields

as the keys.

 You have several options to fetch data from MySQL.

 The most frequently used option is to use function mysql_fetch_array()


Getting Data From MySql Database: Example

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, salary FROM employee';
mysql_select_db(‘Bit');
$result = mysql_query( $sql, $conn );
96
Getting Data From MySql Database: Example

if(! $ result )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo “id:{$row[‘id']} <br> ".
“name: {$row[‘name']} <br> ".
“salary: {$row['salary']} <br> ".
"------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
97

?>
Getting Data From MySql Database: Example

 NOTE: Always remember to put curly brackets when you want


to insert an array value directly into a string.
 In above example the constant MYSQL_ASSOC is used as the
second argument to mysql_fetch_array()
 so that it returns the row as an associative array. With an
associative array you can access the field by using their name
instead of using the index.
 PHP provides another function called mysql_fetch_assoc()
98

which also returns the row as an associative array.


Getting Data From MySql Database: Example

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, salary FROM employee';
mysql_select_db(‘Bit'); 99

$result = mysql_query( $sql, $conn );


Getting Data From MySql Database: Example

if(! $result )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
echo "EMP ID :{$row[‘id']} <br> ".
"EMP NAME : {$row[‘name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
100
Getting Data From MySql Database: Example

<?php
include(“conn.php");
mysql_select_db(“MyDB”,$conn);
$sql=“select * from employee”;
$result = mysql_query($sql,$conn);
If(!$result)
die(“Unable to query:”.mysql_err());
while($row=mysql_fetch_row($result)){
for($i=0;$i<count($row);$i++)
print “$row[$i]”;
print”<br>”;
}
mysql_close($link);
?>
Reading Assignment

PHP Date and Time

PHP Mathematical Functions


Part III
….
PHP OOP
What is OOP?
Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and functions.

OOP has several advantages over procedural programming:

 OOP is faster and easier to execute

 OOP provides a clear structure for the programs

 OOP makes the code easier to maintain, modify and debug

 OOP makes it possible to create full reusable applications with less


code and shorter development time
Set By:-Tesfahun N. 104
What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.

 class is a template for objects, and an object is an instance of a


class.

When the individual objects are created, they inherit all the
properties and behaviors from the class, but each object will have
different values for the properties.

Set By:-Tesfahun N. 105


Cont.

Set By:-Tesfahun N. 106


What is Class in Case of OOP?
Let's assume we have a class named Fruit.
 A Fruit can have properties like name, color, weight, etc.
We can define variables like $name, $color, and $weight to hold the
values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit
all the properties and behaviors from the class, but each object will have
different values for the properties.
A class is defined by using the class keyword, followed by the name of the
class and a pair of curly braces ({}).
All its properties and methods go inside the braces:
<?php
Syntax
class Fruit { // code goes here such as properties and methods...
}
Set By:-Tesfahun N. 107
?>
Cont.
Below we declare a class named Fruit consisting of two properties
($name and $color) and two methods set_name() and get_name()
for setting and getting the $name property:
<?php
class Fruit {
  // Properties
  public $name;
  public $color;
  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
?> Set By:-Tesfahun N. 108
What is Objects
Classes are nothing without objects!

We can create multiple objects from a class.

Each object has all the properties and methods defined in


the class, but they will have different property values.

Objects of a class is created using the new keyword.

In the example below, $apple and $banana are instances


of the class Fruit:

Set By:-Tesfahun N. 109


Cont.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}//object
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Set By:-Tesfahun N. 110
PHP - instanceof
You can use the instanceof keyword to check if
an object belongs to a specific class:
Example
<?php

$apple = new Fruit();

var_dump($apple instanceof Fruit);

?>

Set By:-Tesfahun N. 111


Cont.

Set By:-Tesfahun N. 112


Example

Set By:-Tesfahun N. 113


Access Modifiers
Properties and methods can have access modifiers which
control where they can be accessed.

There are three access modifiers:

 public - the property or method can be accessed from


everywhere. This is default
 protected - the property or method can be accessed
within the class and by classes derived from that class
 private - the property or method can ONLY be accessed
within the class
Set By:-Tesfahun N. 114
Cont.
<?php
class Fruit {
  public $name;
  protected $color;
  private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

Set By:-Tesfahun N. 115


PHP - What is Inheritance?
Inheritance in OOP When a class derives from
another class.
The child class will inherit all the public and
protected properties and methods from the parent
class.
 In addition, it can have its own properties and
methods.
An inherited class is defined by using the extends
keyword.

Set By:-Tesfahun N. 116


Cont.

Set By:-Tesfahun N. 117


Outline
<?php
class Fruit { • Example Explained
  public $name;
  public $color;  The Strawberry class is inherited from
  public function __construct($name,
$color) {    $this->name = $name; the Fruit class.
    $this->color = $color;   }
  public function intro() {
    echo "The fruit is {$this->name}  This means that the Strawberry class
and the color is {$this->color}.";
  }} can use the public $name and $color
// Strawberry is inherited from Fruit properties as well as the public
class Strawberry extends Fruit {
  public function message() { __construct() and intro() methods from
    echo "Am I a fruit or a berry? ";
the Fruit class because of inheritance.
  }}
$strawberry = new
Strawberry("Strawberry", "red");  The Strawberry class also has its own
$strawberry->message();
$strawberry->intro(); method: message().
?>

Set By:-Tesfahun N. 118


Function Overloading in PHP
• Function overloading is a feature that permits
making creating several methods with a similar name
that works differently from one another in the type
of the input parameters it accepts as arguments.

• Example

• Let us now see an example to implement function


overloading−
Set By:-Tesfahun N. 119
Cont.
<?php
class Shape {
const PI = 3.142 ;
function __call($name,$arg){
if($name == 'area')
switch(count($arg)){
case 1 : return self::PI * $arg[0] ;
case 2 : return $arg[0] * $arg[1];
}
} }
$circle = new Shape();
echo $circle->area(3);
echo "</br>";
$rect = new Shape();
echo $rect->area(8,6);
?> Set By:-Tesfahun N. 120
Thank you

Set By:-Tesfahun N. 121

You might also like