0% found this document useful (0 votes)
21 views62 pages

10 PHP

The document provides an overview of PHP syntax, including various tag styles, variable types, and data structures such as arrays. It covers fundamental concepts like comments, operators, decision-making structures, loops, and the use of HTML forms in PHP. Additionally, it discusses PHP's case sensitivity, magic constants, and includes practical code examples throughout.

Uploaded by

anupkumarlal58
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views62 pages

10 PHP

The document provides an overview of PHP syntax, including various tag styles, variable types, and data structures such as arrays. It covers fundamental concepts like comments, operators, decision-making structures, loops, and the use of HTML forms in PHP. Additionally, it discusses PHP's case sensitivity, magic constants, and includes practical code examples throughout.

Uploaded by

anupkumarlal58
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

PHP

Dr. Alekha Kumar Mishra


PHP Syntax
● Canonical PHP tags
– <?php...?>
● Short-open (SGML-style) tags
– <?...?>
● ASP-style tags
– <%...%>
● HTML script tags
– <script language="PHP">...</script>

Dr. Alekha Kumar Mishra


Hello World with PHP
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>

Dr. Alekha Kumar Mishra


send HTML to the browser
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type"
content="text/html; charset=utf-8" />
<title>Hello, World!</title>
</head>
<body>
<p>The following was created by PHP:
<?php
echo "<span style=\"font-weight:bold;\">Hello, world!</span>";
?> </p>
</body>
</html>
4

Dr. Alekha Kumar Mishra


Comments in PHP
Multi-lines printing
Single-line comments <?
<? # First Example
# This is a comment, and print <<<END
# This is the second line of the comment This uses the "here document" syntax to output
// This is a comment too. Each style comments only multiple lines with $variable interpolation. Note
that the here document terminator must appear
?> on a line with just a semicolon no extra
Multi-lines comments whitespace!
<? END;
# Second Example
/* This is a comment with multiline print "This spans
Author : Mohammad Mohtashim multiple lines. The newlines will be
Purpose: Multiline Comments Demo output as well";
Subject: PHP ?>
*/
?>

**PHP is whitespace insensitive


5

Dr. Alekha Kumar Mishra


PHP is case sensitive
<html>
<body>
<?
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
Variable capital is 67
Variable CaPiTaL is

Dr. Alekha Kumar Mishra


More about PHP syntax
● A statement in PHP is any expression that is
followed by a semicolon (;)
● smallest building blocks of PHP are the
indivisible tokens
– Numbers (3.14159), strings (.two.), variables ($two),
constants (TRUE)
● We can always put (group) a sequence of
statements anywhere by enclosing them in a set
of curly braces

Dr. Alekha Kumar Mishra


PHP variables
● All variables in PHP are denoted with a leading dollar sign ($).
● A variable holds the value of its most recent assignment.
● Variables are assigned with the = operator.
● Variables can, but do not need, to be declared before assignment.
● Variables in PHP do not have intrinsic types
– a variable does not know in advance about the types of the value it will hold.
● Variables used before they are assigned have default values.
● PHP automatically converts types from one to another whenever
necessary.
● The print() function can be used to print variables
– print($var);

Dr. Alekha Kumar Mishra


PHP datatypes
● Integers:
● Doubles:
● Booleans:
● NULL: is a special type that only has one value: NULL.
● Strings:
● Arrays:
● Objects: instances of programmer-defined classes
● Resources: are special variables that hold references to
resources external to PHP (such as database connections)

Dr. Alekha Kumar Mishra


Variables example

$int_var = 12345;
$many = 2.2888800;
$var= TRUE;
$my_var = NULL;
$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
define("MINSIZE", 50); //constant type

10

Dr. Alekha Kumar Mishra


PHP Magic constants
● __LINE__ : The current line number of the file.
● __FILE__ : The full path and filename of the file. If
used inside an include,the name of the included file is
returned.
● __FUNCTION__ : The function name.
● __CLASS__ : The class name.
● __METHOD__ : The class method name.

11

Dr. Alekha Kumar Mishra


PHP–Variables
● Local variables
● Global variables
● Static variables

12

Dr. Alekha Kumar Mishra


PHP Operators
● Arithmatic operators
+,-,*,/,%,++,--
● Relational operators
==, !=,<,>,>=,>=
● Logical operators
and, or, &&, ||, !
● Assignment Operators
=, +=, -=, *=, /=, %=
● Conditional Operators ( ? :)

13

Dr. Alekha Kumar Mishra


Decision Making (if ...else)
<html> <html>
<body> <body>

<?php <?php
$d = date("D"); $d = date("D");

if ($d == "Fri") if ($d == "Fri")


echo "Have a nice weekend!"; echo "Have a nice weekend!";
else
echo "Have a nice day!"; elseif ($d == "Sun")
?> echo "Have a nice Sunday!";

</body> else
</html> echo "Have a nice day!";
?>

</body>
</html>

14

Dr. Alekha Kumar Mishra


Decision Making (switch)
<html>
<body>
case "Fri":
<?php echo "Today is Friday";
$d = date("D"); break;

switch ($d){ case "Sat":


case "Mon": echo "Today is Saturday";
echo "Today is Monday"; break;
break;
case "Sun":
case "Tue": echo "Today is Sunday";
echo "Today is Tuesday"; break;
break;
default:
case "Wed": echo "Wonder which day is this ?";
echo "Today is Wednesday"; }
Break; ?>
case "Thu":
echo "Today is Thursday"; </body>
break; </html>

15

Dr. Alekha Kumar Mishra


<html>
<body>

loops <?php
$i = 0;
$num = 50;

while( $i < 10) {


$num--;
$i++;
}
<html>
<body> echo ("Loop stopped at i = $i and num =
$num" );
<?php ?>
$a = 0;
$b = 0; </body>
</html>
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b =


$b" );
?>

</body>
16
</html>
Dr. Alekha Kumar Mishra
loops
<html>
<html> <body>
<body>
<?php
<?php $array = array( 1, 2, 3, 4, 5);
$i = 0;
$num = 0; foreach( $array as $value ) {
echo "Value is $value <br />";
do { }
$i++; ?>
}
</body>
while( $i < 10 ); </html>
echo ("Loop stopped at i = $i" );
?>

</body>
</html>
break keyword is used to terminate the
execution of a loop prematurely.

continue keyword is used to halt the current


iteration of a loop but it does not terminate the
loop.
17

Dr. Alekha Kumar Mishra


Arrays in PHP
● Numeric array − An array with a numeric index.
Values are stored and accessed in linear fashion.
● Associative array − An array with strings as
index. This stores element values in association
with key values rather than in a strict linear index
order.
● Multidimensional array − An array containing
one or more arrays and values are accessed
using multiple indices

18

Dr. Alekha Kumar Mishra


Numeric Array
html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html> 19

Dr. Alekha Kumar Mishra


Associative Arrays
<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("steven" => 2000, "john" => 1000, "liza" => 500);

echo "Salary of Steven is ". $salaries['steven'] . "<br />";


echo "Salary of John is ". $salaries['john']. "<br />";
echo "Salary of Liza is ". $salaries['liza']. "<br />";

/* Second method to create array. */


$salaries['steven'] = "high";
$salaries['john'] = "medium";
$salaries['liza'] = "low";

echo "Salary of Steven is ". $salaries['steven'] . "<br />";


echo "Salary of John is ". $salaries['john']. "<br />";
echo "Salary of Liza is ". $salaries['liza']. "<br />";
?>

</body>
</html>
20

Dr. Alekha Kumar Mishra


Multidimensional Arrays
<html>
<body>
/* Accessing multi-dimensional array values */
<?php echo "Marks for marchello in physics : " ;
$marks = array( echo $marks['marchello']['physics'] . "<br />";
"marchello" => array (
"physics" => 35, echo "Marks for qadir in maths : ";
"maths" => 30, echo $marks['qadir']['maths'] . "<br />";
"chemistry" => 39
), echo "Marks for louis in chemistry : " ;
echo $marks['louis']['chemistry'] . "<br />";
"qadir" => array ( ?>
"physics" => 30,
"maths" => 32, </body>
"chemistry" => 29 </html>
),

"louis" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

21

Dr. Alekha Kumar Mishra


strings
● Dot (.) is used to concatenate two strings
● Escape sequences beginning with backslash (\) are
replaced with special characters
● Variable names (starting with $) are replaced with
string representations of their values.
● strlen() function is used to find the length of a string.
● strpos() function is used to search for a string or
character within a string.

22

Dr. Alekha Kumar Mishra


String example
<?php
$variable = "NIT";
$literally = 'the $variable will not print!\\n';

print($literally);
print "<br />";

$literally = "this will print $variable!\\n";

print($literally);
?>

23

Dr. Alekha Kumar Mishra


Random number generators
● rand generate a random integer
● rand ( void ) : int
● rand ( int $min , int $max ) : int
● srand seeds the random number generator
with seed or with a random value if no seed is
given.
<?php
srand(mktime());
echo(rand());
?>
24

Dr. Alekha Kumar Mishra


<html>
<body>
An example
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );

switch( $num ) {
case 1: $image_file = "/php/images/logo.png";
break;

case 2: $image_file = "/php/images/php.jpg";


break;

case 3: $image_file = "/php/images/logo.png";


break;

case 4: $image_file = "/php/images/php.jpg";


break;
}
echo "Random Image : <img src=$image_file />";
?>

</body>
</html> 25

Dr. Alekha Kumar Mishra


Using HTML forms
● Any form element in an HTML page will
automatically be available to our PHP scripts
● The PHP default variable $_PHP_SELF is used
in action field when the same PHP script is
required be called
● The PHP header() function supplies raw HTTP
headers to the browser
● It can be used to redirect it to another location

26

Dr. Alekha Kumar Mishra


An example of_PHP_SELF
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}

echo "Welcome ". $_POST['name']. "<br />";


echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html> 27

Dr. Alekha Kumar Mishra


Redirection example
<?php
if( $_POST["location"] ) {
$location = $_POST["location"];
header( "Location:$location" ); <html>
<body>
exit();
} <p>Choose a site to visit :</p>
?>
<form action = "<?php $_SERVER['PHP_SELF'] ?>"
method ="POST">
<select name = "location">.

<option value = "http://www.tutorialspoint.com">


Tutorialspoint.com
</option>

<option value = "http://www.google.com">


Google Search Page
</option>

</select>
<input type = "submit" />
</form>

</body>
</html>
28

Dr. Alekha Kumar Mishra


Include function
● The include() function takes all
the text in a specified file and menu.php
<a href="https://www.google.co.in/">Google</a> -
copies it into the file that uses the <a href="https://www.youtube.com/l">Youtube</a> -
include function. <a href="https://www.amazon.in/">Amazon</a> -
<a href="https://www.facebook.com/">Facebook</a>
● In case of error in loading a file,
the include() function generates a
warning but the script will <html>
continue execution. <body>
● require() function is similar to <?php include("menu.php"); ?>
include() funcion except that <p>This is an example to show how to
require() function generates a include PHP file!</p>
fatal error and halt the execution
of the script </body>
</html>

29

Dr. Alekha Kumar Mishra


User-defined function
<html>
<?php
<head>
//function with parameters
<title>Writing PHP Function</title>
function addFunction($num1, $num2) {
</head>
$sum = $num1 + $num2;
<body>
return $sum;
<?php
}
/* Defining a PHP Function */
function writeMessage() {
$sm=addFunction(10, 20);
echo "A simple function";
echo "Sum is : $sm";
}
?>
/* Calling a PHP Function */ <?php
writeMessage(); // function parameter by reference
?> function addFive($num) {
$num += 5;
</body> }
</html>
function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />"; 30
?>
Dr. Alekha Kumar Mishra
User-defined function
● A function can return a value <html>
<head>
using the return statement <title>Dynamic Function Calls</title>
</head>
– return $sum; <body>
<?php
● A function can return more than function sayHello() {
one value from a function using echo "Hello<br />";
return array(1,2,3,4). }
function sayHi() {
● We can also set a parameter to echo "Hi<br />";
}
have a default value if the
function's caller doesn't pass it $function_holder = "sayHello";
$function_holder();
using assignment operator $function_holder = "sayHi";
$function_holder();
– function myfunc($param = NULL)
{ ... } ?>

</body>
</html>
31

Dr. Alekha Kumar Mishra


Superglobals
● A few special associative arrays that can be accessed
from anywhere in a PHP file
● The $_SERVER superglobal gives information about
server and client
– $_SERVER['PHP_SELF'] The filename of the currently
executing script, relative to the document root
– $_SERVER[‘SERVER_ADDR’] " server IP
– $_SERVER[‘REMOTE_ADDR’] " client IP
– $_SERVER[‘HTTP_USER_AGENT’] " client OS and
browser

32

Dr. Alekha Kumar Mishra


GET request
● GET request passes information via the URL
– http://www.yourdomain.com/yourpage.php?
firstparam=firstvalue&secondparam=secondvalue
● GET requests are sent via the URL, and can thus be
cached, bookmarked, shared, etc
● The PHP provides $_GET superglobal associative array
to access all the sent information using GET method.
– $_GET[‘firstparam’] => ‘firstvalue’
– $_GET[‘secondparam’] => ‘secondvalue'

33

Dr. Alekha Kumar Mishra


GET Example
<!DOCTYPE html>
<html> <html>
<body> <head>
<title>Welcome Page</title>
<form action="http://localhost/welcome.php" <body>
method="get" target="_top" > <?php
Name:<br> echo "Welcome <b>". $_GET['name'].
<input type="text" name="name" value=""> "</b><br />";
<br> echo "You are a <b>". $_GET["desg"] ."</b> of
Designation:<br> <b>".$_GET['org']. "</b>.";
<input type="text" name="desg" value="">
<br> ?>
Organisation:<br> </body>
<input type="text" name="org" value=""> </html>
<br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

34

Dr. Alekha Kumar Mishra


Post request
● GET requests are limited by the length of the URL
● POST requests are not exposed in the URL and should be used
for sensitive data
● There is no limit to the amount of information passed via POST
● The PHP provides $_POST associative array to access all the
sent information using POST method.
● PHP $_REQUEST variable contains the contents of both
$_GET, $_POST, and $_COOKIE;
● It can be used to get the result from form data sent with both the
GET and POST methods

35

Dr. Alekha Kumar Mishra


POST Example
<!DOCTYPE html> <html>
<html> <head>
<body> <title>Welcome Page</title>
<form <body>
action="http://localhost/postex.php" <?php
method="POST" target="_top" > $mobno=$_POST["mob"];
Name:<br> $fdig=substr($mobno,0,1);
<input type="text" name="name" $ldig=substr($mobno,-1);
value="">
<br> echo "Hello!! <b>". $_POST['name'].
Mobile Number:<br> "</b><br />";
<input type="text" name="mob" echo "The first digit of your mobile no is <b>".
value=""> $fdig."</b><br /> ";
<br><br> echo "The last digit of your mobile no is <b>".
<input type="submit" value="Submit"> $ldig."</b><br /> ";
</form> ?>
</body>
</body> </html>
</html>

36

Dr. Alekha Kumar Mishra


Request Example
<!DOCTYPE html> <html>
<html> <head>
<body> <title>Request Example</title>
<body>
<form
<?php
action="http://localhost/requestex.php" $num1=(int)$_REQUEST["num1"];
method="POST" target="_top" > $num2=(int)$_REQUEST["num2"];
First Number:<br> echo "GCD is
<input type="text" name="num1" ".euclid_gcd($num1,$num2).".<br/>";
value="">
<br> function euclid_gcd($num1,$num2){
Second Number:<br> if($num1 == 0)
<input type="text" name="num2" return $num2;
else
value=""> return euclid_gcd($num2 %
<br><br> $num1, $num1);
<input type="submit" value="Compute }
GCD">
</form> ?>
</body>
</body> </html>
</html>

37

Dr. Alekha Kumar Mishra


PHP Cookies
● There are three steps involved in identifying
returning users by a server:
– Server sends a set of cookies to the browser.
(name, id number etc.)
– Browser stores this information on local machine for
future use.
– For any subsequent request to the web server,
client sends those cookies information to the server
in order to identify the return user.

38

Dr. Alekha Kumar Mishra


Client header with cookie

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

39

Dr. Alekha Kumar Mishra


PHP Cookies
● A PHP script can access to the cookie through
$_COOKIE or $HTTP_COOKIE_VARS[] which
holds all cookie names and values.
● Cookie: name=xyz
– Above cookie can be accessed using
$HTTP_COOKIE_VARS["name"].

40

Dr. Alekha Kumar Mishra


Setting Cookies
● setcookie() function is provided to set a cookie.
● Requires upto six arguments and should be
called before <html> tag.
● For each cookie this function has to be called
separately.
● Syntax : setcookie(name, value, expire, path,
domain, security);

41

Dr. Alekha Kumar Mishra


Setting Cookies
● Arguments:
– Name − This sets the name of the cookie and is stored in an environment
variable called HTTP_COOKIE_VARS.
– Value − This sets the value of the named variable and is the content that
you actually want to store.
– Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st
Jan 1970.
● cookie will become inaccessible after this time.

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.
– Domain − This can be used to specify the domain name in very large
domains and must contain at least two periods to be valid. All cookies are
only valid for the host and domain which created them.
– Security − set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 to sent by regular HTTP
42

Dr. Alekha Kumar Mishra


Example
<?php
setcookie("name", "Steve John", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>

<head>
<title>Setting Cookies with PHP</title>
</head>

<body>
<?php echo "Set Cookies"?>
</body>

</html>

43

Dr. Alekha Kumar Mishra


Accessing Cookies
● Simple way to access <html>
cookie is to use either <head>
<title>Accessing Cookies with PHP</title>
– $_COOKIE, or </head>
– $HTTP_COOKIE_VA
<body>
RS
<?php
● use isset() function to if( isset($_COOKIE["name"]))
check if a cookie is echo "Welcome " . $_COOKIE["name"] . "<br />";
echo “ Age “.$HTTP_COOKIE_VARS["age"] . "<br />";
set or not.
else
● Safe way to delete echo "Sorry... Not recognized" . "<br />";
cookies is to ?>

setcookie with date </body>


</html>
that has already
expired
44

Dr. Alekha Kumar Mishra


PHP Sessions
● A session creates a file in a temporary directory
on the server where registered session variables
and their values are stored.
● This data will be available to all pages on the site
during that visit.
● The location of the temporary file is determined
by a setting in the php.ini file called
session.save_path (this is required to be setup
before using session variable)

45

Dr. Alekha Kumar Mishra


Steps involved in a session
● PHP first creates a unique identifier for that particular session such as
3c7foj34c3jj973hjkop2fc937e3443 ( 32 hexadecimal digits).
● A cookie, PHPSESSID is automatically sent to the user's computer to
store unique session id
● A file is automatically created on the server in the designated temporary
directory and bears the name of the unique identifier prefixed by sess_ ,
– sess_3c7foj34c3jj973hjkop2fc937e3443.
● To retrieve values from a session variable, PHP gets the unique session
identifier string from the PHPSESSID cookie
● Looks in its temporary directory for the file and validate both values.
● A session ends either when the user closes the browser or after a
predetermined period of idle time by the server.

46

Dr. Alekha Kumar Mishra


PHP session
● A PHP session is started by calling the
session_start() function.
● Always recommended to put the call to
session_start() at the beginning of the page.
● Session variables are stored in associative array
called $_SESSION[]
● These variables can be accessed during lifetime of
a session.

47

Dr. Alekha Kumar Mishra


<?php
Example
session_start();

if( isset( $_SESSION['counter'] ) ) {


$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";
?>

<html>

<head>
<title>Setting up a PHP session</title>
</head>

<body>
<?php echo ( $msg ); ?>
</body>
48
</html>
Dr. Alekha Kumar Mishra
Session Destroy
● Use session_destroy() function
– <?php session_destroy(); ?>
● to destroy a single session variable, use unset()
function
– <?php unset($_SESSION['counter']); ?>
● Turn Auto session on
– set session.auto_start variable to 1 in php.ini file

49

Dr. Alekha Kumar Mishra


For session with no cookie
● The constant SID which is defined if a session started
● If the client did'nt send session cookie
– it has the form session_name=session_id
● Otherwise, it expands to an empty string

● ini_set('session.use_cookies', 0);
● ini_set('session.use_only_cookies', 0);
● ini_set('session.use_trans_sid', 1);

50

Dr. Alekha Kumar Mishra


MySQL & PHP

51

Dr. Alekha Kumar Mishra


PHP Web Database Architecture

52

Dr. Alekha Kumar Mishra


MySQL Database Connection
● Through mysqli_connect() function

Opens a new connection to the MySQL server.
● Syntax
– mysqli_connect(host,username,password,dbname,port,socket);

The host name of the server


running database. default the port number
value is localhost:3306. and socket
name or pipe to
attempt to
The username accessing the database. By connect to the
default name of the user that owns the MySQL server
server process.

Specifies the default


The password of the user accessing the database.
database to be used
If not specified then an empty password. 53

Dr. Alekha Kumar Mishra


An Example : dbconnclient
<!DOCTYPE html>
<html>
<body>
<h1> Database Connection Example </h2>
<form action="http://localhost/dbconn.php" method="get" target="_top" >
User Name:<br>
<input type="text" name="uname" value="">
<br><br>
Password:<br>
<input type="password" name="upwd" value="">
<br><br>
DB Host:<br>
<input type="text" name="dbhost" value="localhost:3306" disabled>
<br><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

54

Dr. Alekha Kumar Mishra


An Example : dbconnserver
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = $_GET['dbhost'];
$dbuser = $_GET['uname'];
$dbpass = $_GET['upwd'];
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
</body>
</html>

55

Dr. Alekha Kumar Mishra


Performing queries
● mysqli_query(connection,query,resultmode);

MYSQLI_USE_RESULT
MySQL the query string (To retrieve large amount of
connection data)
variable MYSQLI_STORE_RESULT
(default)

56

Dr. Alekha Kumar Mishra


PHP Data Objects (PDO)
● The PHP Data Objects (PDO) extension defines a lightweight,
consistent interface for accessing databases in PHP.
● Each database driver that implements the PDO interface can
expose database-specific features as regular extension functions.
● Must use a database-specific PDO driver to access a database
server and to use database functions using the PDO extension by
itself.
● Uses the same functions to issue queries and fetch data.
● PDO ships with PHP 5.1, and is available as a PECL extension for
PHP 5.0;
● PDO requires the new OO features in the core of PHP 5

57

Dr. Alekha Kumar Mishra


MySQL connection with PDO
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

//Close connection
$conn->close();

58

Dr. Alekha Kumar Mishra


Executing Query and
Processing Results
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
echo $row["columnname"]. "<br>";
} else {
echo "0 results";

59

Dr. Alekha Kumar Mishra


Example 1: Inserting Data
● insert_data_login.htm or insert_data_login.php
– will take the username and password to connect to the
mysql database for a database name called 'testdb'
● dbinsert.php
– Print the connection status, create session using post data
and redirect to the page to insert data to the database.
● dbinsertdata.php
– Take input for each column of the marksheet table from the
user using a form and self execute to insert the given data to
the table using query.

60

Dr. Alekha Kumar Mishra


Example 2: Performing query and
showing result
db_query_login.htm takes user name and password to
connect to database

dbquery.php displays the status of connection to the


database. On successful connection ask user to input the
registration no for displaying marks details.

dbquerydisp.php displays the result of the query based on


registration field or shows error message.

61

Dr. Alekha Kumar Mishra


Example 3 : Update a mark
db_update_login.htm takes user name, password, and
database name to connect to database

dbupdate.php displays the status of connection to the


database. On successful connection ask user to input the
registration no and updating fields.

dbquerydisp.php displays the result of the update


operation on the table based on registration field or shows
error message.

62

Dr. Alekha Kumar Mishra

You might also like