0% found this document useful (0 votes)
12 views

PHP Final

Uploaded by

SNK GAMERS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

PHP Final

Uploaded by

SNK GAMERS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Web Techology part 2(PHP)

Server side scripting using PHP



PHP is an acronym for Hypertext Preprocessor. PHP is a widely-used open
source scripting language that are executed on the server side.

PHP borrowed its primary syntax from C++ & C.

Many of the programming techniques you’ve previously learned will work in PHP
(assignments, comparisons, loops, etc.) with little to no syntax difference.

There are, however, major changes in how data is manipulated in relationship to
C/C++.

C/C++ are type-specific languages, requiring the user to define a specific,
singular type for each variable that they use.

PHP commonly assigns its variables “by value”, meaning a variable takes on the
value of the source variable (expression) and is assigned to the destination
variable.

A variable can therefore change its type “on the fly”.

Therefore, variables are not declared as they are in most type-specific languages
like C/C++.
What can PHP do

Generate pages and files dynamically.

Create, open, read, write and close files on the server. Collect
data from a web form such as user information, email, phone
number, etc.

Send emails to the users of your website.

Send and receive cookies to track the visitor of your website.
Store, delete, and modify information in your database. Restrict
unauthorized access to your website.

Encrypt data for safe transmission over internet. and many more.
PHP Variables

In PHP, a variable does not need to be declared before adding a
value to it.

PHP automatically converts the variable to the correct data type,
depending on its value.
● After declaring a variable it can be reused throughout the code.
● The assignment operator (=) is used to assign value to a variable.

In PHP, variable can be declared as $var_name = value;
● Example
<html>
<body>
<h1>Declaring Variables</h1>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Naming Conventions for PHP
Variables

All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _).

A variable name cannot contain spaces.
PHP Data Types

The values assigned to a PHP variable may be of different data types including simple
string and numeric types to more complex data types like arrays and objects.
PHP supports total eight primitive data types:
● Integer
● Float
● String
● Booleans
● Array
● Object
● Resource &
● NULL
Operators in PHP – Arithmetic
● + :Addition ( $x + $y) Sum of $x and $y
● - :Subtraction( $x - $y) Difference of $x and $y
● *: Multiplication ($x * $y )Product of $x and $y
● / :Division ($x / $y) Quotient of $x and $y
● %: Modulus ($x % $y )Remainder of $x and $y
Example
<html><?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo "<br>";
echo($x - $y); // 0utputs: 6
echo "<br>";
echo($x * $y); // 0utputs: 40
echo "<br>";
echo($x / $y); // 0utputs: 2.5
echo "<br>";
echo($x % $y); // 0utputs: 2
?>
<html>
Operators in PHP – Comparison
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
Operators in PHP
Increment & Decrement

++$x (Pre-increment Increments $x by one, then returns $x)

$x++ (Post-increment Returns $x, then increments $x by
one)

--$x (Pre-decrement Decrements $x by one, then returns $x)

$x-- (Post-decrement Returns $x, then decrements $x by
one)
● Example
<html>
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo"<br>";
echo $x; // Outputs: 11\
echo"<br>";
$x = 10;
echo $x++; // Outputs: 10
echo"<br>";
echo $x; // Outputs: 11
echo"<br>";
$x = 10;
echo --$x; // Outputs: 9
echo"<br>";
echo $x; // Outputs: 9
$x = 10;
echo"<br>";
echo $x--; // Outputs: 10
echo"<br>";
echo $x; // Outputs: 9
?>
</html>
Operators in PHP – Logical
● and :And ($x and $y True if both $x and $y are true)
● Or: Or ($x or $y True if either $x or $y is true)

xor :Xor ($x xor $y True if either $x or $y is true, but not
both)

&&: And ($x && $y True if both $x and $y are true)

|| :Or( $x || $y True if either $x or $y is true)

! :Not (!$x True if $x is not true)
Operators in PHP – String
● . : Concatenation( $str1.$str2 Concatenation of $str1 and $str2)
● .= :Concatenation assignment ($str1.=$str2 Appends the $str2 to the $str1)
Example:
<html>
<?php
$x = "Hello";
$y = " World!";
echo $x . $y;
echo"<br>";
// Output: HelloWorld!
$x .= $y;
echo $x;
//Output: HelloWorld!
?>
</html>
Object Oriented Programming using

server side scripting
OOP stands for Object-Oriented Programming.

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.
Object-oriented programming has several advantages over procedural
programming:

OOP is faster and easier to execute

OOP provides a clear structure for the programs

OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and 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
PHP - What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.
class

Fruit
Object

objects

Apple
● Banana
● Mango

So, a 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.
Define a Class

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:

Syntax
<?php
class className {
// code goes here...
}
?>
● Note: In a class, variables are called properties and functions are called methods!
Define 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 are created using the new keyword.

In the example below, $apple and $banana are
instances of the class Fruit:
<html>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
</html>
Database
PHP MySQL Database
Connectivity
● With PHP, you can connect to and manipulate databases.
● MySQL is the most popular database system used with PHP.

In order to store or access the data inside a MySQL database, you first need
to connect to the MySQL database server.

PHP offers two different ways to connect to MySQL server:

MySQLi (Improved MySQL) and PDO (PHP Data Objects) extensions.

While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as he name suggests supports
MySQL database only.

MySQLi extension however provides an easier way to connect to, and
execute queries on, a MySQL database server.
Connecting to MySQL Database

In PHP, you can easily connect to MySQL database
using the mysqli_connect() function.

All communication between PHP and the MySQL
database server takes place through this connection.

The connection to the MySQL database server will be
closed automatically as soon as the execution of the
script ends.

However, if you want to close it earlier, you can do this
by simply calling the PHP mysqli_close() function.
Connecting to MySQL Database

Basic Syntax (MySQLi, Procedural way)
$link = mysqli_connect("hostname", "username", "password","database");

Basic Syntax (MySQLi, Object Oriented way)$mysqli = new
mysqli("hostname", "username", "password", "database");

Basic Syntax (PHP Data Objects way)
$pdo = new
PDO("mysql:host=hostname;dbname=database","username","password"
);
Connecting to MySQL Database
<html>
<?php
echo "Now we are connecting database";
echo"<br>";
//creating variables: servername, username and password
$servername = "localhost";
$username = "root";
$password = "";
//connection objec creation
$conn=mysqli_connect($servername, $username, $password);
echo"Connected successfully";
?>
</html>
If fails to connect
<html>
<?php
echo "Now we are connecting database";
echo"<br>";
//creating variables: servername, username and password
$servername = "localhost";
$username = "root";
$password = "p";
//connection objec creation
$conn=mysqli_connect($servername, $username, $password);
//die if not connected
if(!$conn){
//string ctoncatination with.mysqli_connect_error()
die("Unable to connect".mysqli_connect_error());
}
echo"Connected successfully";
?>
</html>
PHP MySQL Create Database
<html>
<?php
echo"<br>";
$servername = "localhost";
$username = "root";
$password = "";
$conn=mysqli_connect($servername, $username, $password);
if(!$conn){
die("Unable to connect".mysqli_connect_error());
}
else{
echo"Connected successfully";
}
$sql = “CREATE DATABASE texasplustwo”;
?>
</html>
Creating table in the database
<html> //creating a table in db "texasplustwo"
<?php $sql = "CREATE TABLE `TexasStudent` ( `Sno.` INT(11) NOT NULL
AUTO_INCREMENT , `Name` VARCHAR(20) NOT NULL , `Address`
$servername = "localhost"; VARCHAR(20) NOT NULL , `Grade` INT(11) NOT NULL , PRIMARY
$username = "root"; KEY (`Sno.`)) ";
$password = ""; $result = mysqli_query($conn, $sql);
//cheacking if the table is created successfully
$database ="texasplustwo";
if ($result ){
$conn=mysqli_connect($servername, $username, $password,
$database); echo "The table is created successfully<br>";
//die if not connected }
if(!$conn){ else{

die("Unable to connect".mysqli_connect_error()); echo "The table was not created because of this
erroe :".mysqli_error($conn);
}
}
else{
echo"Connected successfully"; ?>
} </html>
Before
After
Inserting data into MySql
$sql ="INSERT INTO `TexasStudent` (`Sno.`, `Name`,
<?php `Address`, `Grade`) VALUES ('2', 'harry', 'Kathmandu',
$servername = "localhost"; '12')";

$username = "root"; $result = mysqli_query($conn, $sql);


//cheacking if the table is created successfully
$password = "";
if ($result ){
$database ="texasplustwo";
echo "Data is inserted successfully<br>";
$conn=mysqli_connect($servername, $username,
}
$password,$database);
else{
if(!$conn){
echo "Data is not inserted because of the
die("Unable to connect".mysqli_connect_error()); error :".mysqli_error($conn);
} }
else{ ?>
echo"Connected successfully"; </html>
}
Before
After
Fetching records from MySql
<html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database ="texasplustwo";
$conn=mysqli_connect($servername, $username, $password,$database);
if(!$conn){
die("Unable to connect".mysqli_connect_error());
}
else{
echo"Connected successfully <br>";
}
$sql ="SELECT * FROM `TexasStudent` ";
$result = mysqli_query($conn, $sql);
//records returned
echo mysqli_num_rows($result);
?>
</html>
Display the rows returned by the sql
query
$sql ="SELECT * FROM `TexasStudent` ";
<?php $result = mysqli_query($conn, $sql);
$servername = "localhost"; //records returned
$num = mysqli_num_rows($result);
$username = "root";
echo $num;
$password = "";
echo "<br>";
$database ="texasplustwo"; //Display the rows returned by the sql query
$conn=mysqli_connect($servername, $username, if($num>0){
$password,$database); $row = mysqli_fetch_assoc($result); //fetch record one by one
if(!$conn){ until all the data are fetched
echo var_dump($row);
die("Unable to connect".mysqli_connect_error());
echo "<br>";
} }
else{ ?>
echo"Connected successfully <br>";
}
Displaying the queries in table
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database ="texasplustwo";
$conn=mysqli_connect($servername, $username, $password,$database);
if(!$conn){
die("Unable to connect".mysqli_connect_error());
}
else{
echo"Connected successfully <br>";
}
$sql ="SELECT * FROM `TexasStudent` ";
$result = mysqli_query($conn, $sql);
//records returned
echo mysqli_num_rows($result);
echo "<br>";
echo "<table border = '1'>";// Creating a table
echo "<tr><td>Name</td><td>Address</td><td>Grade</td></tr>"; // defining the table data as
similarly as it is in database
while($row = mysqli_fetch_assoc($result))// fetching the content of table until all the contents
are fetched
{
echo "<tr><td>{$row['Name']}</td><td>{$row ['Address']}</td><td>{$row
['Grade']}</td></tr>"; //Dsiplaying the contents of data
}
echo "</table>";
?>

You might also like