Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

PHP & MySQL

What can Server Scripts Do?


Dynamically edit, change or add any content to a Web
page
Respond to user queries or data submitted from
HTML forms
Access any data or databases and return the
result to a browser
Customize a Web page to make it more useful for
individual users
Provide security since your server code cannot be
viewed from a browser
Server Scripts
Server-side scripting products consist of two
main parts

The scripting language


The scripting engine (which may or may
not be built into the web server)
Why PHP?
PHP stands for PHP: Hypertext Preprocessor
The product was originally named Personal Home
Page Tools

Widely used server side scripting language


Employed to generate Hypertext Markup
Language (HTML) information dynamically

PHP supports many databases like MySQL,


SQLite, PostgreSQL, DB2, MS SQL,
ORACLE, and so on
Websites that use PHP
How PHP
Works?
What do you Need?
PHP server

Text Editor

Web
browser
What is a PHP File?
• PHP files can contain text, HTML tags and
scripts

• PHP files are returned to the browser as plain


HTML
• PHP files have a file extension of ".php",

".php3", or ".phtml"

Developed by Rasmus Lerdorf


Latest Version 7.1.21(Sept 2018)
Basic PHP Syntax
A PHP scripting block always starts with
<?php and ends with ?>
A PHP scripting block can be placed anywhere
in the document (HTML)
Sample:
<?php ->Starting tag

?> ->Ending tag


Example :
<html>
<body>
<?php

/* PHP Code
*/

?>
</body>
</html>
Comments
Single-line comments: # and //

The multiline style of commenting is the same


as in C :
/* your comments */
Example:
<?php
# this is a PHP comment
line

/*
* this is a multi-line PHP
* comment block
*/

?>
Echo
echo is not actually a function (it is a
language construct)
echo (arg1, arg2... )

Example
<?php
echo “Hello This is Sample
Text”;
?>
Echo
Echo accepts multiple arguments

Arguments are separated by commas

<?php
echo “Velalar“, “Engineering",
"College”;
?>
Print
The command print is very similar to echo, with
two important differences

print can accept only one argument

print returns a value, which represents


whether or not the print statement succeeded
The value returned by print is always 1
<?php
print(“3.14159”); // print a
string print(3.14159); // print a
number
?>
Variables & Data
Types
Variable
s Variables can hold different kinds of data
Data type of a variable does not need to be
declared in advance
The name of a variable is Case-sensitive
After the dollar sign, the next character in the
name must be a letter or an underscore
The value of a variable is the value of its most
recent assignment
Data
Types
PHP has eight data
types:
Scalar types
boolean
integer
float
string
Compound types
array
object
Special
types
resources
NULL
Syntax :
$Variable_name=Value;
<?php
$txt="Hello World!";
$x=16;
echo
$txt;
print $x;
?>
PHP Variable
Scopes
Four different variable scopes:
Local
Variable declared within a PHP function is
local
Global
Variable defined outside of any
function
Static
Declared with keyword static
Parameter
Operators in PHP
Arithmetic
Operators
Comparison
Operators Array
Operators Logical
Operators
Arithmetic Operators
Operator Name Description

x+y Addition Sum of x and y

x-y Subtraction Difference of x and y

x*y Multiplication Product of x and y

x/y Division Quotient of x and y

x%y Modulus Remainder of x divided by y

-x Negation Opposite of x

a.b Concatenation Concatenate two strings


Comparison Operators
Operator Name Description

x == y Equal True if x is equal to y

x === y Identical True if x is equal to y, and they are of same type

x != y Not equal True if x is not equal to y

x <> y Not equal True if x is not equal to y

x !== y Not identical True if x is not equal to y, or they are not of same type

x>y Greater than True if x is greater than y

x<y Less than True if x is less than y

x >= y Greater than or equal to True if x is greater than or equal to y

x <= y Less than or equal to True if x is less than or equal to y


Array Operators
Operator Name Description

x+y Union Union of x and y

x == y Equality True if x and y have the same key/value pairs

True if x and y have the same key/value pairs


x === y Identity
in the same order and are of the same type

x != y Inequality True if x is not equal to y

x <> y Inequality True if x is not equal to y

x !== y Non-identity True if x is not identical to y


Logical Operators
Operator Name Description Example

x=6
x and y And True if both x and y are true y=3
(x < 10 and y > 1) returns true
x=6
x or y Or True if either or both x and y are true y=3
(x==6 or y==5) returns true
x=6
x xor y Xor True if either x or y is true, but not both y=3
(x==6 xor y==3) returns false
x=6
x && y And True if both x and y are true y=3
(x < 10 && y > 1) returns true
x=6
x || y Or True if either or both x and y are true y=3
(x==5 || y==5) returns false
x=6
!x Not True if x is not true y=3
!(x==y) returns true
Automatic type conversion
PHP does a good job of automatically converting
types when necessary

$pi = 3 + 0.14159;

Manual Type Casting


$pi=(float)3+0.14;
Functions
Functions
The real power of PHP comes from its
functions.
There are more than 700 built-in functions

Syntax
function
functionName(arg1,arg2,….argn)
{
code to be executed;
}
<html>
<body>
<?php
function writeName()
{
echo “Sukhesh Raj";
}
echo "My name
is ";
writeName();
?>
</body>
</html>
Function – Return the values
Function return a value, using the return
statement
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
PHP functions:
Array functions HTTP functions
Calendar functions LibXML
Date functions functions Mail
Directory functions functions Math
Error functions functions Misc
Filesystem functions functions
Filter functions MySQL functions
FTP functions SimpleXML
functions
String functions
XML Parser
functions
Arrays
•Index Arrays
•Associative Arrays
•Multidimensional
Arrays
Arrays
Arrays are known as compound data types
Can hold multiple values indexed by numbers or
strings

Indexed Arrays
Arrays with numerical keys

Associative Arrays
keys can also be named with strings

Multidimensional arrays
Arrays containing one or more arrays
Indexed
Arrays
To create an empty array $a = array()
Array with values
$arr_name=array(“value1”,”value2”,”val
ue3”);

Ex:
<?php
$cars=array("Saab","Volvo","BMW”)
;
?>
$myArray = array(0 => 10, 1 => 20, 2 =>
30) ;
Assign the index manually
<?php
$cars[0]="Saab"
;
$cars[1]="Volvo
";
$cars[2]="BMW
";
$cars[3]="Toyot
a";
?>
Associative
Arrays
The key portion of an array can also
consist of character strings

$array_name*key+=“value”;
Traversing
Array
<?php
$myArray = array(‘sno' => 1, ‘rollno' =>
“12itr001”, 'fname' => "Peter", 'initial' =>
"B",
'lname' => "MacIntyre", 'phone' =>
“04294-226570") ; foreach ($myArray as $key
=> $value)
{
echo "the Key is: " . $key . " and its value is: " .
$value . "<br/>";
}
Multidimensional Arrays
In a multidimensional array, each
element in the main array can also be
an array. And each element in the
sub-array can be an array, and so on.
Example

<!DOCTYPE html> echo $cars[0][0].": In stock:


<html> ".$cars[0][1].", sold:
".$cars[0][2].".<br>";
<body>
echo $cars[1][0].": In stock:
".$cars[1][1].", sold:
<?php ".$cars[1][2].".<br>";
$cars = array ( echo $cars[2][0].": In stock:
array("Volvo",22,18), ".$cars[2][1].", sold:
array("BMW",15,13), ".$cars[2][2].".<br>";
array("Saab",5,2), echo $cars[3][0].": In stock:
".$cars[3][1].", sold:
array("Land Rover",17,15)
".$cars[3][2].".<br>";
);
?> </body> </html>
Output
Array Functions
count() - returns the number of elements in an
array
sizeof() - returns the number of elements in an
array alias of count().

Unset(arrayname) - destroys a given array

arsort() – Sorts associative array in descending


order

asort() – Sorts associative array in ascending


order
Array Functions
rsort() - Sorts an indexed array in descending
order

sort() - Sorts an indexed array in ascending


order
asort() sorts an associative array in ascending
order, according to the value.

arsort() to sort an associative array in


descending order, according to the value.

count() or sizeof() function returns the


Strings
String Variables in
PHP
String is simply a collection of characters
Strings can be contained within either single or
double quotation marks or a combination of the
two

Double quote
Allows variable expansion (variable content
insertion)

Single Quote
Does not allows variable expansion
Double quote
<?php
$eng = “Engineering" ;
$place = “Thindal" ;
$string = “Velalar $eng College,
$place"; echo $string ."<br>";
$string = "He said \"go away\" to
me" ;
$eco $string;
?>
Single Quote
<?php
$eng = “Engineering" ;
$place = “Thindal" ;
$string = ‘Velalar $eng .’College,’.
$place’;

echo $string
$string = ‘Velalar’. $eng .’College,’.
$place’; echo $string ;

$s = '<br/>He said "go away" to


me'; echo $s;
String Functions
String Functions
Strlen(string)
returns the length of the provided string

str_word_count(string)
counts the number of words in a given string

strtolower(string) -converts a string to


lowercase

Strtoupper(string) - converts a string to


uppercase
String Functions
strcmp(string 1,string2) – Compare strings

strrev() – to reverse a string


str_repeat(string,repeat) - repeats a string a
specified number of times

nl2br - HTML line breaks before all newlines in a


string
String Functions
trim: Remove whitespace content from both
ends

ltrim:Remove whitespace content from left


end

rtrim: Remove whitespace content from right


end
<?php
$string = " The quick brown fox jumps over the lazy
dog " ; var_dump(ltrim($string));
echo "<br/>";
var_dump(rtrim($string
)); echo "<br/>";
var_dump(trim($string)
);
?>
The var_dump function displays structured
information about variables/expressions including its
type and value
strpos() - Search For a Text Within a
String functions String
<?php
echo strpos("Hello world!", "world");
strlen() - Return the Length of a
?>
String
Outputs:
<?php 6
echo strlen("Hello world!"); str_replace() - Replace Text Within a
?>
String
Outputs:
<?php
12 echo str_replace("world", "Dolly", "Hell
str_word_count() - Count Words in
o world!");
a String
?>
<?php
Outputs:
echo str_word_count("Hello world!"); Hello Dolly!
?>
strtolower()-returns string in
Outputs: lowercase letter
2 <?php
strrev() - Reverse a String $str="My name is RAJ";
<?php $str=strtolower($str);
echo strrev("Hello world!");
echo $str;
?>
?>
Outputs:
Output:
!dlrow olleH
my name is raj
HTML
Forms
$_POST
$_GET
$_REQUEST
HTML Forms and PHP
HTML forms are used to pass data to a server
An HTML form can contain input elements (text
fields, checkboxes, radio-buttons, submit buttons
and more )
To collect values in a form there are two array
variables
$_POST[input_field_name]
$_GET[input_field_name]

Ex <input type=text name=firstname/>


$_POST*‘firstname’+;
$_GET*‘firstname’+;
$_GET
Varaible
$_GET variable is used to collect values in a
form with method="get“
ex <form action=“index.php" method="get">

Only limited amount of information can be


passed
GET method sends input to the handling script
publicly
Ex:http://www.myweb.com/access.php?login=1&lo
gname
=“Fred”
A page generated by a form that used the GET
$_POST
Variable
Form will use method =post
ex <form action=“index.php"
method=“POST">
The information is less visible to the web
user
It cant be bookmarked
While Reload it ask for conformation
message
$_REQUEST
An associative array that by default
contains the contents of $_GET, $_POST
and $_COOKIE.
Validation
Functions
empty()
Determine whether a variable is empty or not (
non 0 value)
isset()
Determine if a variable is set and is not NULL
Control Structures and Loops
Control Structures {if, if – else, if elseif else,
switch }
Loops { while, for, do – while}
Control structures
The two broad types of control
structures
Branches
If
Switch
Loops
For
While
Do-while
If-statement
If(condition)
{
statements;
}
Example:
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice
weekend!";
?>
if...elseif....else Statement
if (condition)
code to be executed if condition is
true;
elseif (condition)
code to be executed if condition is
true;
else
code to be executed if condition is
false;
Switch
switch(expressio
n)
{
case
value-1:
statemen
t;
break;
case
value-2:
statemen
While
while (condition)
{
code to be
executed;
}
<?php
$count = 1;
while ($count <= 10)
{
print (“count is
$count<BR/>”);
$count = $count + 1;
}
?>
do
{
code to be
executed;
}
while (condition);
<?php
$i=1
;
do
{
$i++;
echo "The number is " . $i .
"<br />";
}
while ($i<=5);
?>
For loop
for (init; condition;
increment)
{code to be
executed;
}
For each
The foreach loop is used to loop
through arrays.
foreach ($array as $value)
{
code to be executed;
}
COOKIE AND
SESSION
What is a Cookie?
A cookie is a small file that the server
embeds on the user's computer
Each time the same computer requests a
page with a browser, it will send the
cookie too
It is possible to create and retrieve cookie
values using PHP
Why Cookie?
Marginally easier to create and
retrieve
Require Slightly less work from the
server
Persist over a longer period of time
Create Cookies
It must be sent from the server to the
client
Cookies are sent using setcookie()
setcookie() function must appear
BEFORE the
<html> tag
Syntax
setcookie(name, value, expire, path,
domain, security);
Name − sets the name of the cookie
Value − is the content that you actually want to
store.
Expiry − expiry time of the cookie. If this
parameter is not set then cookie will
automatically expire when the Web Browser is
closed.
Path − This specifies the directories for which the
cookie is valid. A single forward slash character
permits the cookie to be valid for all directories.
Domain − All cookies are only valid for the
host and domain which created them.
Security − This can be set to 1 to specify that the
cookie should only be sent by secure
transmission using HTTPS otherwise set to 0
which mean cookie can be sent by regular HTTP.
Delete a cookie
By setting the expiration date is in the
past

Setcookie(‘cookiename’,’’,time()-600);
Another way
Setcookie(‘cookiename’,’’);
Setcookie(‘cookiename’, FALSE);
SESSION
Session variables hold information about
one single user
The data is available to all pages in
one application
Session data is stored on the server
Benefits over cookies
Session are generally more secure
It will store more information
It will work even cookies is not enabled
Starting a PHP Session
First start session using session_start()
session_start() function must appear
BEFORE the
<html> tag
Example
<?php session_start(); ?>

<html>
<body>
……..
</body>
</html>
Creating a Session
Record data by assigning values to the
$_SESSION array

$_SESSION*‘Sess_var_name’+=value;

Example

$_SESSION*‘username’+=“
Raja”;
Delete a Session
Variable
To delete some session data the
following functions are used

unset()
used to free the specified session
variable

session_destroy()
To reset session and delete all stored
session data
SSI – Server Side Include
Include /
require
PHP include and require Statements
To insert the content of one PHP file into
another PHP file before the server
executes it
include and require statements are
used to insert useful codes written in
other files
require will produce a fatal error and stop
the script
include will only produce a warning and
the script will continue
PHP and
MySQL
Data base connectivity and Data
manipulations
Introduction to Database
A database is a collection of data
Databases implemented through a
computer are created within software

That software known as a database


application
What is MySQL
It is a database system used on the web

It is very fast, reliable, and easy to use

It supports standard SQL

Free to download and use


Developed, distributed, and supported by
Oracle Corporation

PHP+MySQL
PHP combined with MySQL are
cross-platform
Connecting to MySQL
mysqli_connect() / mysql_connect()
It open a new connection to the MySQL server
Syntax
mysqli_connect(host,username,password,dbname,port,
socket);
Parameter Description
host Optional. Either a host name or an IP address

username Optional. The MySQL user name

password Optional. The password to log in with

dbname Optional. The default database to be used when performing


queries
portSpecifies the port number to attempt to connect to
the MySQL server
socket
Specifies the socket or named pipe to be used
Close Connection
mysqli_close(connection)
closes a non-persistent MySQL
connection
Example
<?php
$con=mysqli_connect(‘localhost’.’root’,’’,’
mydb’); If(!$con)
//failed
else
// success
mysqli_close($c
on);
?>
mysqli_query()

mysqli_query(connection,query,resultm
ode);
function executes a query on a MySQL database
Connection Specifies the MySQL connection to use

query Specifies the query string

Optional.
A constant. Either:
resultmode •MYSQLI_USE_RESULT (Use this if we have to retrieve large
amount of data)
•MYSQLI_STORE_RESULT (This is default)
Handle with Database

Create Database
CREATE DATABASE db_name
Select the created Database
mysqli_select_db(db_name,conne
ction)

Drop a Database
<?php
$con =
mysqli_connect("localhost",“root","");
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
else {
echo "Database connected“; }
if (mysqli_query($con,"CREATE DATABASE
my_db"))
{ echo "Database
created“; } else
{ echo "Error creating database: " .
mysql_error();
}
Output
db_connection.php
index.php
<?php
function OpenCon()
{ <?php
$dbhost = "localhost"; include 'db_connection.php';
$dbuser = "root"; $conn = OpenCon();
$dbpass = "1234"; echo "Connected Successfully";
$db = "vcet"; CloseCon($conn);
$conn = new mysqli($dbhost, ?>
$dbuser, $dbpass,$db) or
die("Connect failed: %s\n". $conn ->
error); Output

return $conn;
}

function CloseCon($conn)
{
$conn -> close();
}

?>
MySQL Data types
There are three main
types
Text
Numbers
Dates/Times
Tex
Ttype Size Description
CHAR[Length] Length bytes A fixed-length field from 0 to
255 characters long.
VARCHAR(Length) String length + 1 A fixed-length field from 0 to 255
bytes characters long.
TINYTEXT String length + 1 A string with a maximum length
bytes of 255 characters
TEXT String length + 2 A string with a maximum length
bytes of 65,535 characters.
MEDIUMTEXT String length + 3 A string with a maximum length
bytes of 16,777,215 characters.
LONGTEXT String length + 4 A string with a maximum length
bytes of 4,294,967,295 characters.
TINYINT[Length] 1 byte Range of -128 to 127 or 0 to 255
unsigned.
SMALLINT[Length] 2 bytes Range of -32,768 to 32,767 or 0 to
65,535 unsigned.
Number
Type Size Description
INT[Length] 4 bytes Range of -2,147,483,648 to
2,147,483,647 or 0 to
4,294,967,295 unsigned
BIGINT[Length] 8 bytes Range of -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 or 0
to 18,446,744,073,709,551,615
unsigned
FLOAT 4 bytes A small number with a
floating decimal point.
DOUBLE[Length, 8 bytes A large number with a
Decimals] floating decimal point.
DECIMAL[Length, Length +1 bytes or A DOUBLE stored as a string,
Decimals] Length + 2 bytes allowing for a fixed decimal
point.
Date and Time
Type Size Description

DATE 3 bytes In the format YYYY-MM-DD

DATETIME 8 bytes In the format YYYY-MM-DD HH:MM:SS.

TIMESTAM 4 bytes In the format YYYYMMDDHHMMSS;


P acceptable range ends in the year 2037.
TIME 3 bytes In the format of HH:MM:SS.

ENUM 1 or 2 bytes Short for enumeration, that is, each


column can have one of several possible
values.
SET 1, 2, 3, 4, or 8 Like ENUM except that each column can
bytes have more than one of several possible
values.
Create
Table
CREATE TABLE statement is used to create a
table in MySQL
CREATE TABLE
table_name
(column_name1
data_type,
column_name2
data_type,
column_name3 data_type,……..
)
<?php
$con =
mysqli_connect("localhost",“root","“,”my_db”);

// Create table
$sql = "CREATE TABLE
Persons (
FirstName
varchar(15),
LastName
varchar(15), Age int
)";
// Execute query
mysqli_query($con,
$sql);
INSERT DATA
INSERT INTO table_name
VALUES (value1, value2,
value3,...)

INSERT INTO table_name


(column1, column2,
column3,...)
VALUES (value1, value2,
value3,...)
SELECT
SELECT * FROM TABLENAME;

mysqli_fetch_array()
function fetches a result row as an
associative array, a numeric array, or
both
mysqli_fetch_row()
function fetches one row from a result-set
and returns it as an enumerated array
WHERE
WHERE clause is used to extract only those
records that fulfill a specified criterion
Syntax
SELECT
column_name(s)
FROM table_name
WHERE column_name = value

$result = mysql_query("SELECT * FROM


Persons WHERE FirstName='Peter'");
ORDER BY
The keyword is used to sort the data in a record
set
The ORDER BY keyword sort the records in
ascending
order by default.
To sort the records in a descending order, use the
DESC
keyword.
Syntax
SELECT
column_name(s)
FROM table_name
Update
UPDATE statement is used to modify data in a
table UPDATE table_name
SET column1=value,
column2=value2,... WHERE
some_column=some_value
Example
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName =
'Griffin'");
Delete
FROM statement is used to delete records
from a database table.
Syntax
DELETE FROM table_name
WHERE some_column = some_value
FILE UPLOAD
HTML <form> enctype
Attribute
enctype attribute specifies how the form-data
should be encoded when submitting it to the
server
<form enctype="value">
Value Description

application/x-www-form-urlencoded Default. All characters are encoded before sent

No characters are encoded. This value is


multipart/form-data required when you are using forms that have a
file upload control

text/plain Spaces are converted to "+" symbols, but no special characters are encoded
Upload (File/Image)
$_FILES System array containing the
uploaded file inform
$_FILES['file']['name']
The original name of the file on the client machine
$_FILES['file']['type']
The mime type of the file (such as “image/jpeg”)
$_FILES['file']['size']
The size, in bytes, of the uploaded file
$_FILES['file']['tmp_name']
The temporary filename of the file in which the
uploaded file was stored on the server
$_FILES['file']['error']
Any error code associated with this file uploadation
Move a File to Destination
move_uploaded_file(file,newloc)
Used to move the uploaded file to
destination
file - Specifies the file to be moved
newloc - Specifies the new location for
the file
Check Whether file exist or not
file_exists(loc/filename)
function checks whether file/ directory
exists or not
Example Upload Form : sample.php
<html>
<body>
<form action="upload.php"
method="post"
enctype="multipart/form-data">
<input type="file" name="f" /><br>
<input type="submit" name="submit"
value="Submit">
</form>
</body>
</html>
Upload.php
<?php
if ($_FILES["f"]["error"] > 0)
{
echo "Error: " . $_FILES["f"]["error"] . "<br>";
}
else
if(file_exists("up/".$_FILES['f']['name']))
{
echo "FILE ALREADY EXISTS";
}
else
move_uploaded_file($_FILES['f']['tmp_name'],"up/".$_FILES['f']['name']);
?>

You might also like