UNIT 4-PHP
UNIT 4-PHP
UNIT 4-PHP
Chapter 4 – PHP
MySql: Connecting to MySql server using PHP, creating new database and
tables, reading and displaying table data, Inserting, detection and
updating records in database table using PHP..
Introduction:
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• It is a widely-used, open source scripting language
• PHP scripts are executed on the server
• It is free to download and use
• It is powerful enough to be at the core of the biggest
blogging system on the web (WordPress)!
• It is deep enough to run the largest social network
(Facebook)!
• It is also easy enough to be a beginner's first server side
language!
• Runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.)
• Compatible with almost all servers used today (Apache,
IIS, etc.)
• Supports a wide range of databases
• Easy to learn and runs efficiently on the server side
PHP Can:
• generate dynamic page content
• create, open, read, write, delete, and close files on the
server
• collect form data
1 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
2 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
3 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
_____________________________________________________________
Variables:
Creating/Declaring PHP Variables:
• In PHP, a variable starts with the $ sign, followed by the
name of the variable.
• A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
• Rules for PHP variables:
o starts with the $ sign, followed by the name of
the variable
o must start with a letter or the underscore
character
o cannot start with a number
o can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
o Case-sensitive.
• Example:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
The scope of variables:
• The scope of a variable is the part of the script where the
variable can be referenced/used.
• PHP has three different variable scopes:
o local
o global
o static
4 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
5 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
6 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
?>
<?php
// program to demonstrate in PHP 7 using const keyword
const TEXT = 'PHP PROGRAMMING!';
echo TEXT;
echo constant("TEXT");
?>
Data Types:
Variables can store data of different types, and different data
types can do different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String:
• A string is a sequence of characters, like "Hello world!".
• can be any text inside quotes. You can use single or
double quotes:
Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
7 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
?>
PHP Integer:
• An integer data type is a non-decimal number between -
2,147,483,648 and 2,147,483,647.
• Rules for integers:
o must have at least one digit
o must not have a decimal point
o can be either positive or negative
• Integers can be specified in three formats: decimal (10-
based), hexadecimal (16-based - prefixed with 0x) or
octal (8-based - prefixed with 0)
• In the following example $x is an integer. The PHP
var_dump() function returns the data type and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float:
• A float (floating point number) is a number with a
decimal point or a number in exponential form.
• In the following example $x is a float. The PHP
var_dump() function returns the data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
8 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
PHP Boolean:
• A Boolean represents two possible states: TRUE or
FALSE.
$x = true;
$y = false;
• Booleans are often used in conditional testing. You will
learn more about conditional testing in a later chapter
of this tutorial.
PHP Array:
• An array stores multiple values in one single variable.
• In the following example $cars is an array. The PHP
var_dump() function returns the data type and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Object:
• An object is a data type which stores data and
information on how to process that data.
• In PHP, an object must be explicitly declared.
Example:
<?php
class Car {
function Car() {
$this->model = "VW"; }
}
// create an object
$herbie = new Car();
// show object properties
9 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
echo $herbie->model;
?>
PHP NULL Value:
• Null is a special data type which can have only one
value: NULL.
• A variable of data type NULL is a variable that has no
value assigned to it.
• Variables can also be emptied by setting the value to
NULL
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource:
• The special resource type is not an actual data type. It
is the storing of a reference to functions and resources
external to PHP.
• A common example of using the resource data type is a
database call.
____________________________________________________________
Functions:
• A function is a block of statements that can be used
repeatedly in a program.
• will not execute immediately when a page loads.
• will be executed by a call to the function.
10 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
Example:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Function Arguments:
• Information can be passed to functions through
arguments. An argument is just like a variable.
• Arguments are specified after the function name, inside
the parentheses. You can add as many arguments as
you want, just separate them with a comma.
Example:
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
11 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
12 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
Indexed Arrays:
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at
0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing
the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
Associative Arrays:
• Associative arrays are arrays that use named keys that you
assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
13 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Multidimensional Arrays:
• A multidimensional array is an array containing one or
more arrays.
Example:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
<?php
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>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold:
".$cars[3][2].".<br>";
?>
_______________________________________________________
Processing a Web form:
• Forms are used to collect user input
14 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
15 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
16 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
}
else if(strlen($p)<6)
{
$flag=false;
$msg="Password should be minimum of 6
characters";
}
if($flag==false)
echo $msg;
else
echo "Login Success <br> Welcome $u";
?>
Introduction to MYSQL:
• MySQL is an open source, fast reliable, and flexible
relational database management system, used with
PHP.
• It is a database system, used for developing web-based
software applications.
• used for both small and large applications.
• It is a relational database management
system (RDBMS).
• Fast, reliable and flexible and easy to use.
• Supports standard SQL (Structured Query Language).
• Free to download and use.
• Presently developed, distributed, and supported by
Oracle Corporation.
• Written in C, C++.
Main Features of MySQL:
• MySQL server design is multi-layered with independent
modules.
17 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername,
$username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
echo "Connected successfully";
Create
?> a MySQL Database:
18 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername,
$username, $password);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
19 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username,
$password, $dbname);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername,
$username, $password, $dbname);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname,
lastname, email)
VALUES ('John', 'Doe',
'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created
successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername,
$username, $password, $dbname);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM
MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row =
mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name:
" . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
22 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername,
$username, $password, $dbname);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
23 Chapter 4 - PHP
FULL STACK TECHNOLOGIES
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername,
$username, $password, $dbname);
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe'
WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
24 Chapter 4 - PHP