SlideShare ist ein Scribd-Unternehmen logo
1 von 62
Downloaden Sie, um offline zu lesen
PHP/MySQL TutorialIntroduction to Database
By:
Prof. Jogeswar Tripathy
NIIS,Bhubaneswar
March 3, 2019
1
What is PHP?
 PHP == „PHP Hypertext Pre-processor‟
 Open-source, server-side scripting language
 Used to generate dynamic web-pages
 PHP scripts reside between reserved PHP tags
 This allows the programmer to embed PHP scripts
within HTML pages
March 3, 20192
What is PHP (cont‟d)
 Interpreted language, scripts are parsed at run-time
rather than compiled beforehand
 Executed on the server-side
 Source-code not visible by client
 „View Source‟ in browsers does not display the PHP
code
 Various built-in functions allow for fast development
 Compatible with many popular databases
March 3, 20193
3 Tier architecture
PHP script
Remote
services
Web Server
(Apache, IIS)
Browser
(IE, FireFox,
Opera)
Desktop
(PC or MAC)
Database
Database
Server
SQL
Client
application
HTTP
HTML
Web Service
tables
DHTML
SMS
vision
touch
voice
SMS system
March 3, 20194
PHP advantages
 Any changes to header or footer only require editing of a
single file.
 This reduces the amount of work necessary for site
maintenance and redesign.
 Helps separate the content and design for easier
maintenance
Page 1
Content
Page 5
Content
Page 3
Content
Page 2
Content
Page 4
Content
Header
Footer
March 3, 20195
What does PHP code look like?
 Structurally similar to C/C++
 Supports procedural and object-oriented paradigm
(to some degree)
 All PHP statements end with a semi-colon
 Each PHP script must be enclosed in the reserved
PHP tag
<?php
…
?>
March 3, 20196
Comments in PHP
 Standard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines */
March 3, 20197
Variables in PHP
 PHP variables must begin with a “$” sign
 Case-sensitive ($Foo $foo $fOo)
 Global and locally-scoped variables
 Global variables can be used anywhere
 Local variables restricted to a function
or class
 Certain variable names reserved by PHP
 Form variables ($_POST, $_GET)
 Server variables ($_SERVER)
 Etc.
March 3, 20198
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
$foo = ($foo * 7); // Multiplies foo by 7
$bar = ($bar * 7); // Invalid expression
?>
March 3, 20199
Echo
 The PHP command „echo‟ is used to
output the parameters passed to it
 The typical usage for this is to send data to
the client‟s web-browser
 Syntax
 echo string arg1 [, string argn...]
March 3, 201910
Echo example
 Notice how echo „5x5=$foo‟ outputs $foo rather
than replacing it with 25
 Strings in single quotes („ ‟) are not interpreted
or evaluated by PHP
 This is true for both variables and character escape-
sequences (such as “n” or “”)
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo „5x5=$foo‟; // Outputs 5x5=$foo
?>
March 3, 201911
Arithmetic Operations
 $a - $b // subtraction
 $a * $b // multiplication
 $a / $b // division
 $a += 5 // $a = $a+5
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
March 3, 201912
Concatenation
 Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>
Hello PHP
March 3, 201913
Output
Escaping the Character
 If the string has a set of double quotation
marks that must remain visible, use the 
[backslash] before the quotation marks to
ignore and display them.
<?php
$heading=“”Computer Science””;
Print $heading;
?>
“Computer Science”
March 3, 201914
Output
PHP Control Structures
if (expr) statement
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
March 3, 201915
if ($foo == 0) {
echo „The variable foo is equal to 0‟;
}
else if (($foo > 0) && ($foo <= 5)) {
echo „The variable foo is between 1 and 5‟;
}
else {
echo „The variable foo is equal to „.$foo;
}
March 3, 201916
PHP Control Structures
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
default:
echo „Enter correct option‟;
}
?>
March 3, 201917
PHP Control Structures
Loops
 while (condition) {statements;}
<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>
hello PHP. hello PHP. hello PHP.
March 3, 201918
Output
Loops
 for (expr1; expr2; expr3)
statement
 <?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
March 3, 201919
Loops
 <?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo “$value n”;
}
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value);//break the
reference
?>
March 3, 201920
Loops
 foreach ($arr as $key => $value) {
echo "Key:$key; Value:$value<br />n";
}
 break ends execution of the current for, foreach,
while, do-while or switch structure.
 continue is used within looping structures to skip the
rest of the current loop iteration and continue
execution at the condition evaluation and then the
beginning of the next iteration.
March 3, 201921
Arrays
 An array in PHP is actually an ordered
map which maps values to keys.
 An array can be thought of in many
ways:
 Linearly indexed array , list (vector), hash
table (which is an implementation of a
map), dictionary, collection, stack (LIFO),
queue (FIFO)
March 3, 201922
Arrays
 Kinds of arrays:
 numeric arrays.
 associative arrays.
 multi dimensional arrays.
March 3, 201923
Arrays
 In numeric arrays each key value corresponds to
numeric values.
 They can be divided into two categories
1.automatic numeric array index.
2.manual array numeric index.
automatic numeric array index
<?php
$x=array(1,2,3);
print_r($x);
?>
array(0=>1,1=>2,2=>3)
March 3, 201924
Output :
Arrays
 Manual array numeric index
<?php
$x[2]=10;
$x[3]=50;//$x=array(2=>10,3=>50);
echo $x[2]; echo $x[3];
?>
 Associative arrays
In associated arrays each ID associated with its value
<?php
$x=array(“ab”=>1,”cd”=>2,”xy”=>3);
print_r($x);
?>
March 3, 201925
Arrays
 Multidimensional Arrays-An array contains one or more
arrays
<?php
$z=array(array(10,20,30),array(40,50,60));
print_r($z);
?>
Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 )
[1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) )
March 3, 201926
Arrays
<?php
$x=array(“ab”=>1,array(2,3,4),”cd
”=>8);
print_r($x);
?>
Array ( [“ab”] => 1 [0] => Array ( [0] => 2
[1] => 3 [2] => 4 ) [”cd”] => 8 )
March 3, 201927
Arrays
<?php
$x=array(3=>4,array(2,3,4),5);
print_r($x);
?>
Array ( [3] => 4 [4] => Array ( [0] => 2
[1] => 3 [2] => 4 ) [5] => 5 )
March 3, 201928
Arrays
Array operations
 sort
 ksort
 rsort
 krsort
 array_merge
 array_combine
 array_intersect
March 3, 201929
Date Display
$datedisplay=date(“yyyy/m/d”);
print $datedisplay;
$datedisplay=date(“l, F J, Y”);
print $datedisplay;
Sunday, March 3, 2019
2019/3/3
March 3, 201930
Output :
Output :
Month, Day & Date Format Symbols
M Jan
F January
m 01
n 1
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
March 3, 2019 31
Functions
 Functions MUST be defined before then can be
called
 Function headers are of the format
 Unlike variables, function names are not case
sensitive
function functionName($arg_1, $arg_2, …, $arg_n)
March 3, 201932
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3); // Store
the function
echo $result_1; // Outputs 36
echo foo(12, 3); // Outputs 36
?>
March 3, 201933
Include Files
 include “header.php”;
 include (“footer.php”);
 This inserts files; the code in files will be
inserted into current code.
 require is identical to include except
upon failure it will also produce a fatal
E_COMPILE_ERROR level error. In other
words, it will halt the script whereas
include only emits a warning (E_WARNING)
which allows the script to continue.
March 3, 201934
Include Files
 The include_once statement includes and
evaluates the specified file during the
execution of the script.
 This is a behavior similar to the include
statement, with the only difference being
that if the code from a file has already been
included, it will not be included again.
 The require_once statement is identical to
require except PHP will check if the file has
already been included, and if so, not include
(require) it again
March 3, 201935
PHP - Forms
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit"
value="Submit">
<input type="submit" name="cancel"
value="Cancel">
</form>
March 3, 201936
PHP - Forms
<?php
…
$term=$_REQUEST[“sterm”];
…
?>
<form action="form.php" method="post">
<input type=“text" name=“sterm"
value=“<?= $term ?>">
</form>
March 3, 201937
MySQL Connectivity
 mysql_connect()
 The mysql_connect()function opens a non-
persistent MySQL connection.
 This function returns the connection on success, or
FALSE and an error on failure. You can hide the
error output by adding an '@' in front of the
function name.
 Syntax
 mysql_connect(server,user,pwd,newlink,cl
ientflag)
March 3, 201938
MySQL Connectivity
Parameter Description
server Specifies the server to connect to
user Specifies the username to log in with.
pwd Specifies the password to log in with.
newlink If a second call is made to mysql_connect() with the
same arguments, no new connection will be
established; instead, the identifier of the already
opened connection will be returned
clientflag •MYSQL_CLIENT_SSL - Use SSL encryption
•MYSQL_CLIENT_COMPRESS - Use compression protocol
•MYSQL_CLIENT_IGNORE_SPACE - Allow space after
function names
•MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout
seconds of inactivity before closing the connection
March 3, 201939
MySQL Connectivity
 Example:
<?php
$con =
mysql_connect("localhost","mysql_user","mysql
_pwd");
if (!$con){
die('Could not connect: „.mysql_error());
}
echo 'Connected successfully';
mysql_close($con);
?>
March 3, 201940
MySQL Connectivity
 mysql_close()
 The mysql_close() function closes a non-
persistent MySQL connection.
 This function returns TRUE on success, or
FALSE on failure.
 Syntax:
 mysql_close(connection)
Parameter Description
connection Specifies the MySQL connection to
close. If not specified, the last
connection opened by
mysql_connect() is used.
March 3, 201941
MySQL Connectivity
 mysql_select_db()
 The mysql_select_db() function sets the active MySQL
database.
 This function returns TRUE on success, or FALSE on
failure.
 Syntax:
 mysql_select_db(database,connection)
Parameter Description
database Required. Specifies the database to select.
connection Optional. Specifies the MySQL connection. If
not specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
March 3, 201942
MySQL Connectivity
<?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db",
$con);
if (!$db_selected){
die ("Can't use test_db : “.
mysql_error());
}
mysql_close($con);
?>
March 3, 201943
MySQL Connectivity
 mysql_query()
 The mysql_query() function executes a query on a
MySQL database.
 This function returns the query handle for SELECT
queries, TRUE/FALSE for other queries, or FALSE on
failure.
 Syntax
 mysql_query(query,connection)
Parameter Description
query Required. Specifies the SQL query to send
(should not end with a semicolon)
connection Optional. Specifies the MySQL connection. If
not specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
March 3, 201944
MySQL Connectivity
<?php
$con =
mysql_connect("localhost",”root",”admin");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con)){
echo "Database my_db created";
}
else{
echo "Error creating database:" .
mysql_error();
}
?>
March 3, 201945
MySQL Connectivity
<?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db", $con);
if (!$db_selected){
die ("Can't use test_db : “. mysql_error());
}
$sql="SELECT * FROM Person where name=„$uname‟";
mysql_query($sql,$con);
mysql_close($con);
?>
March 3, 201946
MySQL Connectivity
 mysql_fetch_array()
 The mysql_fetch_array() function returns a
row from a recordset as an associative array
and/or a numeric array.
 This function gets a row from the
mysql_query() function and returns an array
on success, or FALSE on failure or when
there are no more rows.
 Syntax
 mysql_fetch_array(data,array_type)
March 3, 201947
MySQL Connectivity
Parameter Description
data Required. Specifies which data pointer to use. The
data pointer is the result from the mysql_query()
function
array_type Optional. Specifies what kind of array to
return.Possible values:
•MYSQL_ASSOC - Associative array
•MYSQL_NUM - Numeric array
•MYSQL_BOTH - Default. Both associative and
numeric array
March 3, 201948
MySQL Connectivity
 mysql_fetch_row()
 The mysql_fetch_row() function returns a row from
a recordset as a numeric array.
 This function gets a row from the mysql_query()
function and returns an array on success, or FALSE on
failure or when there are no more rows.
 Syntax
 mysql_fetch_row(data)
Parameter Description
data Required. Specifies which data pointer to use.
The data pointer is the result from the
mysql_query() function
March 3, 201949
MySQL Connectivity
<?php
echo "<table>";
while ($row = mysql_fetch_row($result)) {
echo "<tr><td>".$row[0]
."</td><td>".$row[1].
"</td><td>".$row[2]."</td><td>".
$row[3]."</td></tr>";
}
echo "</table>";
?>
March 3, 201950
MySQL Connectivity
<?php
echo "<table>";
while ($row = mysql_fetch_array($result))
{
echo "<tr><td>{$row[„ID‟]}
</td><td>{$row[1]}
</td><td>{$row[2]}</td><td>
${row[„mailid‟]}</td></tr>";
}
echo "</table>";
?>
March 3, 201951
Cookies
 The setcookie() function is used to
create cookies. Should be called
before <html> tag.
 setcookie(name, [value], [expire],
[path], [domain], [secure]);
 <?php setcookie("uname", $name,
time()+36000); ?>
 This sets a cookie named "uname" -
that expires after ten hours.
 Either a blank value or a time in
the past makes the cookie expired.
March 3, 201952
Cookies
 To access a cookie, refer to the cookie name
as a variable or use $_COOKIE array. The
isset() checks whether the cookie is set or
not
<html> <body>
<?php
if (isset($uname))// isset($_Cookie[$uname])
echo "Welcome " . $_Cookie[$uname].
"!<br />";
else
echo "You are not logged in!<br />"; ?>
?>
</body> </html>
March 3, 201953
Cookies
Benefit of Cookies :
 Cookies are used for authenticating,
tracking, and maintaining specific
information about users
 Personalised home pages
 Electronic shopping carts.
March 3, 201954
Why use sessions
 A normal HTML website will not pass data
from one page to another
 All information is forgotten when a new
page is loaded
 Many websites need to pass user data from
one page to another
 for tasks like a shopping cart, which requires
data(the user's selected product) to be
remembered from one page to the next
 Using PHP sessions is one solution.
March 3, 201955
 Need for data to stored on the server
 Unique session information for each user
 Transient data, only relevant for short
time
 Data does not contain secret information
 Similar to Cookies, but it is stored on
the server
 More secure, once established, no data
is sent back and forth between the
machines
 Works even if cookies are disabled
 Example: we want to count the number of
“hits” on our web page.
March 3, 201956
When should you use sessions?
Sessions
 The session_start() function is used
to create a session. Should be
called before <html> tag.
<?php
session_start();
?>
March 3, 201957
Sessions
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 0;
else
$_SESSION['count']++;
?>
March 3, 201958
Sessions
 session_unregister(´varname´);
unregisters a session variable
 session_destroy() destroys a
session
March 3, 201959
March 3, 201960
Session Example 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have
accessed this page " .
$_SESSION["intVar"] . "times.</p>";
?>
March 3, 201961
Session Example 2
<?php session_start();?>
<?php
$thisPage = $_SERVER['PHP_SELF'];
$pageNameArray = explode('/', $thisPage);
$pageName = $pageNameArray[count($pageNameArray) - 1];
print "The name of this page is: $pageName<br/>";
$nameItems = explode(„.', $pageName);
$sessionName = $nameItems[0];
print "The session name is $sessionName<br/>";
if (!isset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = 0;
print "This is the first time you have visited this page<br/>";
}
else {
$_SESSION[$sessionName]++;
}
print "<h1>You have visited this page " . $_SESSION[$sessionName] .
" times</h1>";
?>
March 3, 201962

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Php mysql
Php mysqlPhp mysql
Php mysql
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Programming with php
Programming with phpProgramming with php
Programming with php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbai
 

Ähnlich wie PHP/MySQL Tutorial Introduction

Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners musrath mohammad
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbaivibrantuser
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/tutorialsruby
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting languageElmer Concepcion Jr.
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
Php Tutorial | Introduction Demo | Basics
 Php Tutorial | Introduction Demo | Basics Php Tutorial | Introduction Demo | Basics
Php Tutorial | Introduction Demo | BasicsShubham Kumar Singh
 
Learning of Php and My SQL Tutorial | For Beginners
Learning of Php and My SQL Tutorial | For BeginnersLearning of Php and My SQL Tutorial | For Beginners
Learning of Php and My SQL Tutorial | For BeginnersRatnesh Pandey
 

Ähnlich wie PHP/MySQL Tutorial Introduction (20)

Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbai
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Php Tutorial | Introduction Demo | Basics
 Php Tutorial | Introduction Demo | Basics Php Tutorial | Introduction Demo | Basics
Php Tutorial | Introduction Demo | Basics
 
Learning of Php and My SQL Tutorial | For Beginners
Learning of Php and My SQL Tutorial | For BeginnersLearning of Php and My SQL Tutorial | For Beginners
Learning of Php and My SQL Tutorial | For Beginners
 
Php My SQL Tutorial | beginning
Php My SQL Tutorial | beginningPhp My SQL Tutorial | beginning
Php My SQL Tutorial | beginning
 

Kürzlich hochgeladen

Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Tapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the FunnelTapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the Funneljen_giacalone
 
SD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxSD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxjanettecruzeiro1
 
Government polytechnic college-1.pptxabcd
Government polytechnic college-1.pptxabcdGovernment polytechnic college-1.pptxabcd
Government polytechnic college-1.pptxabcdshivubhavv
 
Design Inspiration for College by Slidesgo.pptx
Design Inspiration for College by Slidesgo.pptxDesign Inspiration for College by Slidesgo.pptx
Design Inspiration for College by Slidesgo.pptxTusharBahuguna2
 
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)amitlee9823
 
The Art of Batik, template ppt aesthetic
The Art of Batik, template ppt aestheticThe Art of Batik, template ppt aesthetic
The Art of Batik, template ppt aestheticTiaFebriani
 
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceanilsa9823
 
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts ServiceVVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Servicearoranaina404
 
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...Pooja Nehwal
 
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call GirlsCBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girlsmodelanjalisharma4
 
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130Suhani Kapoor
 
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...BarusRa
 
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...ranjana rawat
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵anilsa9823
 
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Booking open Available Pune Call Girls Nanded City 6297143586 Call Hot India...
Booking open Available Pune Call Girls Nanded City  6297143586 Call Hot India...Booking open Available Pune Call Girls Nanded City  6297143586 Call Hot India...
Booking open Available Pune Call Girls Nanded City 6297143586 Call Hot India...Call Girls in Nagpur High Profile
 

Kürzlich hochgeladen (20)

Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Paharganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
young call girls in Vivek Vihar🔝 9953056974 🔝 Delhi escort Service
 
Tapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the FunnelTapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the Funnel
 
SD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxSD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptx
 
Government polytechnic college-1.pptxabcd
Government polytechnic college-1.pptxabcdGovernment polytechnic college-1.pptxabcd
Government polytechnic college-1.pptxabcd
 
Design Inspiration for College by Slidesgo.pptx
Design Inspiration for College by Slidesgo.pptxDesign Inspiration for College by Slidesgo.pptx
Design Inspiration for College by Slidesgo.pptx
 
꧁❤ Hauz Khas Call Girls Service Hauz Khas Delhi ❤꧂ 9999965857 ☎️ Hard And Sex...
꧁❤ Hauz Khas Call Girls Service Hauz Khas Delhi ❤꧂ 9999965857 ☎️ Hard And Sex...꧁❤ Hauz Khas Call Girls Service Hauz Khas Delhi ❤꧂ 9999965857 ☎️ Hard And Sex...
꧁❤ Hauz Khas Call Girls Service Hauz Khas Delhi ❤꧂ 9999965857 ☎️ Hard And Sex...
 
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
 
The Art of Batik, template ppt aesthetic
The Art of Batik, template ppt aestheticThe Art of Batik, template ppt aesthetic
The Art of Batik, template ppt aesthetic
 
Call Girls Service Mukherjee Nagar @9999965857 Delhi 🫦 No Advance VVIP 🍎 SER...
Call Girls Service Mukherjee Nagar @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SER...Call Girls Service Mukherjee Nagar @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SER...
Call Girls Service Mukherjee Nagar @9999965857 Delhi 🫦 No Advance VVIP 🍎 SER...
 
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Aminabad Lucknow best Night Fun service
 
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts ServiceVVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
 
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...Kurla Call Girls Pooja Nehwal📞 9892124323 ✅  Vashi Call Service Available Nea...
Kurla Call Girls Pooja Nehwal📞 9892124323 ✅ Vashi Call Service Available Nea...
 
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call GirlsCBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
 
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
VIP Call Girls Service Bhagyanagar Hyderabad Call +91-8250192130
 
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
 
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
 
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Brookefield Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Booking open Available Pune Call Girls Nanded City 6297143586 Call Hot India...
Booking open Available Pune Call Girls Nanded City  6297143586 Call Hot India...Booking open Available Pune Call Girls Nanded City  6297143586 Call Hot India...
Booking open Available Pune Call Girls Nanded City 6297143586 Call Hot India...
 

PHP/MySQL Tutorial Introduction

  • 1. PHP/MySQL TutorialIntroduction to Database By: Prof. Jogeswar Tripathy NIIS,Bhubaneswar March 3, 2019 1
  • 2. What is PHP?  PHP == „PHP Hypertext Pre-processor‟  Open-source, server-side scripting language  Used to generate dynamic web-pages  PHP scripts reside between reserved PHP tags  This allows the programmer to embed PHP scripts within HTML pages March 3, 20192
  • 3. What is PHP (cont‟d)  Interpreted language, scripts are parsed at run-time rather than compiled beforehand  Executed on the server-side  Source-code not visible by client  „View Source‟ in browsers does not display the PHP code  Various built-in functions allow for fast development  Compatible with many popular databases March 3, 20193
  • 4. 3 Tier architecture PHP script Remote services Web Server (Apache, IIS) Browser (IE, FireFox, Opera) Desktop (PC or MAC) Database Database Server SQL Client application HTTP HTML Web Service tables DHTML SMS vision touch voice SMS system March 3, 20194
  • 5. PHP advantages  Any changes to header or footer only require editing of a single file.  This reduces the amount of work necessary for site maintenance and redesign.  Helps separate the content and design for easier maintenance Page 1 Content Page 5 Content Page 3 Content Page 2 Content Page 4 Content Header Footer March 3, 20195
  • 6. What does PHP code look like?  Structurally similar to C/C++  Supports procedural and object-oriented paradigm (to some degree)  All PHP statements end with a semi-colon  Each PHP script must be enclosed in the reserved PHP tag <?php … ?> March 3, 20196
  • 7. Comments in PHP  Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */ March 3, 20197
  • 8. Variables in PHP  PHP variables must begin with a “$” sign  Case-sensitive ($Foo $foo $fOo)  Global and locally-scoped variables  Global variables can be used anywhere  Local variables restricted to a function or class  Certain variable names reserved by PHP  Form variables ($_POST, $_GET)  Server variables ($_SERVER)  Etc. March 3, 20198
  • 9. Variable usage <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?> March 3, 20199
  • 10. Echo  The PHP command „echo‟ is used to output the parameters passed to it  The typical usage for this is to send data to the client‟s web-browser  Syntax  echo string arg1 [, string argn...] March 3, 201910
  • 11. Echo example  Notice how echo „5x5=$foo‟ outputs $foo rather than replacing it with 25  Strings in single quotes („ ‟) are not interpreted or evaluated by PHP  This is true for both variables and character escape- sequences (such as “n” or “”) <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable echo $bar; // Outputs Hello echo $foo,$bar; // Outputs 25Hello echo “5x5=”,$foo; // Outputs 5x5=25 echo “5x5=$foo”; // Outputs 5x5=25 echo „5x5=$foo‟; // Outputs 5x5=$foo ?> March 3, 201911
  • 12. Arithmetic Operations  $a - $b // subtraction  $a * $b // multiplication  $a / $b // division  $a += 5 // $a = $a+5 <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?> March 3, 201912
  • 13. Concatenation  Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP March 3, 201913 Output
  • 14. Escaping the Character  If the string has a set of double quotation marks that must remain visible, use the [backslash] before the quotation marks to ignore and display them. <?php $heading=“”Computer Science””; Print $heading; ?> “Computer Science” March 3, 201914 Output
  • 15. PHP Control Structures if (expr) statement <?php if ($a > $b) { echo "a is bigger than b"; $b = $a; } ?> <?php if ($a > $b) { echo "a is greater than b"; } else { echo "a is NOT greater than b"; } ?> March 3, 201915
  • 16. if ($foo == 0) { echo „The variable foo is equal to 0‟; } else if (($foo > 0) && ($foo <= 5)) { echo „The variable foo is between 1 and 5‟; } else { echo „The variable foo is equal to „.$foo; } March 3, 201916 PHP Control Structures
  • 17. <?php switch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break; default: echo „Enter correct option‟; } ?> March 3, 201917 PHP Control Structures
  • 18. Loops  while (condition) {statements;} <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP. March 3, 201918 Output
  • 19. Loops  for (expr1; expr2; expr3) statement  <?php $i = 0; do { echo $i; } while ($i > 0); ?> March 3, 201919
  • 20. Loops  <?php $arr = array(1, 2, 3, 4); foreach ($arr as $value) { echo “$value n”; } foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value);//break the reference ?> March 3, 201920
  • 21. Loops  foreach ($arr as $key => $value) { echo "Key:$key; Value:$value<br />n"; }  break ends execution of the current for, foreach, while, do-while or switch structure.  continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. March 3, 201921
  • 22. Arrays  An array in PHP is actually an ordered map which maps values to keys.  An array can be thought of in many ways:  Linearly indexed array , list (vector), hash table (which is an implementation of a map), dictionary, collection, stack (LIFO), queue (FIFO) March 3, 201922
  • 23. Arrays  Kinds of arrays:  numeric arrays.  associative arrays.  multi dimensional arrays. March 3, 201923
  • 24. Arrays  In numeric arrays each key value corresponds to numeric values.  They can be divided into two categories 1.automatic numeric array index. 2.manual array numeric index. automatic numeric array index <?php $x=array(1,2,3); print_r($x); ?> array(0=>1,1=>2,2=>3) March 3, 201924 Output :
  • 25. Arrays  Manual array numeric index <?php $x[2]=10; $x[3]=50;//$x=array(2=>10,3=>50); echo $x[2]; echo $x[3]; ?>  Associative arrays In associated arrays each ID associated with its value <?php $x=array(“ab”=>1,”cd”=>2,”xy”=>3); print_r($x); ?> March 3, 201925
  • 26. Arrays  Multidimensional Arrays-An array contains one or more arrays <?php $z=array(array(10,20,30),array(40,50,60)); print_r($z); ?> Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 ) [1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) ) March 3, 201926
  • 27. Arrays <?php $x=array(“ab”=>1,array(2,3,4),”cd ”=>8); print_r($x); ?> Array ( [“ab”] => 1 [0] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [”cd”] => 8 ) March 3, 201927
  • 28. Arrays <?php $x=array(3=>4,array(2,3,4),5); print_r($x); ?> Array ( [3] => 4 [4] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [5] => 5 ) March 3, 201928
  • 29. Arrays Array operations  sort  ksort  rsort  krsort  array_merge  array_combine  array_intersect March 3, 201929
  • 30. Date Display $datedisplay=date(“yyyy/m/d”); print $datedisplay; $datedisplay=date(“l, F J, Y”); print $datedisplay; Sunday, March 3, 2019 2019/3/3 March 3, 201930 Output : Output :
  • 31. Month, Day & Date Format Symbols M Jan F January m 01 n 1 Day of Month d 01 Day of Month J 1 Day of Week l Monday Day of Week D Mon March 3, 2019 31
  • 32. Functions  Functions MUST be defined before then can be called  Function headers are of the format  Unlike variables, function names are not case sensitive function functionName($arg_1, $arg_2, …, $arg_n) March 3, 201932
  • 33. Functions example <?php // This is a function function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3); // Store the function echo $result_1; // Outputs 36 echo foo(12, 3); // Outputs 36 ?> March 3, 201933
  • 34. Include Files  include “header.php”;  include (“footer.php”);  This inserts files; the code in files will be inserted into current code.  require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. March 3, 201934
  • 35. Include Files  The include_once statement includes and evaluates the specified file during the execution of the script.  This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again.  The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again March 3, 201935
  • 36. PHP - Forms <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form> March 3, 201936
  • 37. PHP - Forms <?php … $term=$_REQUEST[“sterm”]; … ?> <form action="form.php" method="post"> <input type=“text" name=“sterm" value=“<?= $term ?>"> </form> March 3, 201937
  • 38. MySQL Connectivity  mysql_connect()  The mysql_connect()function opens a non- persistent MySQL connection.  This function returns the connection on success, or FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name.  Syntax  mysql_connect(server,user,pwd,newlink,cl ientflag) March 3, 201938
  • 39. MySQL Connectivity Parameter Description server Specifies the server to connect to user Specifies the username to log in with. pwd Specifies the password to log in with. newlink If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned clientflag •MYSQL_CLIENT_SSL - Use SSL encryption •MYSQL_CLIENT_COMPRESS - Use compression protocol •MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names •MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection March 3, 201939
  • 40. MySQL Connectivity  Example: <?php $con = mysql_connect("localhost","mysql_user","mysql _pwd"); if (!$con){ die('Could not connect: „.mysql_error()); } echo 'Connected successfully'; mysql_close($con); ?> March 3, 201940
  • 41. MySQL Connectivity  mysql_close()  The mysql_close() function closes a non- persistent MySQL connection.  This function returns TRUE on success, or FALSE on failure.  Syntax:  mysql_close(connection) Parameter Description connection Specifies the MySQL connection to close. If not specified, the last connection opened by mysql_connect() is used. March 3, 201941
  • 42. MySQL Connectivity  mysql_select_db()  The mysql_select_db() function sets the active MySQL database.  This function returns TRUE on success, or FALSE on failure.  Syntax:  mysql_select_db(database,connection) Parameter Description database Required. Specifies the database to select. connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used. March 3, 201942
  • 43. MySQL Connectivity <?php $con = mysql_connect("localhost", “root", “admin"); if (!$con){ die('Could not connect: '. mysql_error()); } $db_selected = mysql_select_db("test_db", $con); if (!$db_selected){ die ("Can't use test_db : “. mysql_error()); } mysql_close($con); ?> March 3, 201943
  • 44. MySQL Connectivity  mysql_query()  The mysql_query() function executes a query on a MySQL database.  This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.  Syntax  mysql_query(query,connection) Parameter Description query Required. Specifies the SQL query to send (should not end with a semicolon) connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used. March 3, 201944
  • 45. MySQL Connectivity <?php $con = mysql_connect("localhost",”root",”admin"); if (!$con){ die('Could not connect: ' . mysql_error()); } $sql = "CREATE DATABASE my_db"; if (mysql_query($sql,$con)){ echo "Database my_db created"; } else{ echo "Error creating database:" . mysql_error(); } ?> March 3, 201945
  • 46. MySQL Connectivity <?php $con = mysql_connect("localhost", “root", “admin"); if (!$con){ die('Could not connect: '. mysql_error()); } $db_selected = mysql_select_db("test_db", $con); if (!$db_selected){ die ("Can't use test_db : “. mysql_error()); } $sql="SELECT * FROM Person where name=„$uname‟"; mysql_query($sql,$con); mysql_close($con); ?> March 3, 201946
  • 47. MySQL Connectivity  mysql_fetch_array()  The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a numeric array.  This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.  Syntax  mysql_fetch_array(data,array_type) March 3, 201947
  • 48. MySQL Connectivity Parameter Description data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function array_type Optional. Specifies what kind of array to return.Possible values: •MYSQL_ASSOC - Associative array •MYSQL_NUM - Numeric array •MYSQL_BOTH - Default. Both associative and numeric array March 3, 201948
  • 49. MySQL Connectivity  mysql_fetch_row()  The mysql_fetch_row() function returns a row from a recordset as a numeric array.  This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.  Syntax  mysql_fetch_row(data) Parameter Description data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function March 3, 201949
  • 50. MySQL Connectivity <?php echo "<table>"; while ($row = mysql_fetch_row($result)) { echo "<tr><td>".$row[0] ."</td><td>".$row[1]. "</td><td>".$row[2]."</td><td>". $row[3]."</td></tr>"; } echo "</table>"; ?> March 3, 201950
  • 51. MySQL Connectivity <?php echo "<table>"; while ($row = mysql_fetch_array($result)) { echo "<tr><td>{$row[„ID‟]} </td><td>{$row[1]} </td><td>{$row[2]}</td><td> ${row[„mailid‟]}</td></tr>"; } echo "</table>"; ?> March 3, 201951
  • 52. Cookies  The setcookie() function is used to create cookies. Should be called before <html> tag.  setcookie(name, [value], [expire], [path], [domain], [secure]);  <?php setcookie("uname", $name, time()+36000); ?>  This sets a cookie named "uname" - that expires after ten hours.  Either a blank value or a time in the past makes the cookie expired. March 3, 201952
  • 53. Cookies  To access a cookie, refer to the cookie name as a variable or use $_COOKIE array. The isset() checks whether the cookie is set or not <html> <body> <?php if (isset($uname))// isset($_Cookie[$uname]) echo "Welcome " . $_Cookie[$uname]. "!<br />"; else echo "You are not logged in!<br />"; ?> ?> </body> </html> March 3, 201953
  • 54. Cookies Benefit of Cookies :  Cookies are used for authenticating, tracking, and maintaining specific information about users  Personalised home pages  Electronic shopping carts. March 3, 201954
  • 55. Why use sessions  A normal HTML website will not pass data from one page to another  All information is forgotten when a new page is loaded  Many websites need to pass user data from one page to another  for tasks like a shopping cart, which requires data(the user's selected product) to be remembered from one page to the next  Using PHP sessions is one solution. March 3, 201955
  • 56.  Need for data to stored on the server  Unique session information for each user  Transient data, only relevant for short time  Data does not contain secret information  Similar to Cookies, but it is stored on the server  More secure, once established, no data is sent back and forth between the machines  Works even if cookies are disabled  Example: we want to count the number of “hits” on our web page. March 3, 201956 When should you use sessions?
  • 57. Sessions  The session_start() function is used to create a session. Should be called before <html> tag. <?php session_start(); ?> March 3, 201957
  • 59. Sessions  session_unregister(´varname´); unregisters a session variable  session_destroy() destroys a session March 3, 201959
  • 60. March 3, 201960 Session Example 1 <?php session_start(); if (!isset($_SESSION["intVar"]) ){ $_SESSION["intVar"] = 1; } else { $_SESSION["intVar"]++; } echo "<p>In this session you have accessed this page " . $_SESSION["intVar"] . "times.</p>"; ?>
  • 61. March 3, 201961 Session Example 2 <?php session_start();?> <?php $thisPage = $_SERVER['PHP_SELF']; $pageNameArray = explode('/', $thisPage); $pageName = $pageNameArray[count($pageNameArray) - 1]; print "The name of this page is: $pageName<br/>"; $nameItems = explode(„.', $pageName); $sessionName = $nameItems[0]; print "The session name is $sessionName<br/>"; if (!isset($_SESSION[$sessionName])) { $_SESSION[$sessionName] = 0; print "This is the first time you have visited this page<br/>"; } else { $_SESSION[$sessionName]++; } print "<h1>You have visited this page " . $_SESSION[$sessionName] . " times</h1>"; ?>