4th Unit Web
4th Unit Web
4th Unit Web
UNIT IV
SERVER-SIDE PROCESSING AND SCRIPTING – PHP
PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control
and Looping -Arrays - Strings - Functions - File Handling - File Uploading – Email Basics
- Email with attachments -PHP and HTML - Simple PHP scripts - Databases with PHP
<?php
//Write Script here
>
4.1
IT 3401 WEB ESSENTIALS UNIT 4
4.2
IT 3401 WEB ESSENTIALS UNIT 4
Step 5: The web server receives the HTML file from the
interpreter. Step 6: And it sends the webpage back to the browser.
4.2.1 Variables
String variables
Assigning a string value to a variable:
$username = "Fred Smith";
echo $username;
Or you can assign it to another variable like this:
$current_user = $username;
Your first PHP program
<?php // test1.php
$username = "Fred Smith";
echo $username;
echo "<br>";
$current_user = $username;
echo $current_user;
?>
Now you can call it up by entering the following into your browser’s address bar:
http://localhost/test1.php
Numeric variables
Variables don’t contain just strings—they can contain numbers, too.
$count = 17;
4.3
IT 3401 WEB ESSENTIALS UNIT 4
You could also use a floating-point number (containing a decimal point); the syntax is the
same:
$count = 17.5;
In PHP, you would assign the value of $count to another variable or perhaps just echo it to the
web browser
Variable naming rules
When creating PHP variables, you must follow these four rules:
• Variable names must start with a letter of the alphabet or the _ (underscore) character.
• Variable names can contain only the characters a–z, A–Z, 0–9, and _ (underscore).
• Variable names may not contain spaces. If a variable must comprise more than one word, it
should be separated with the _ (underscore) character (e.g., $user_name).
• Variable names are case-sensitive. The variable $High_Score is not the same as the variable
$high_score.
4.2.2 Operators
• Operators are the mathematical, string, comparison, and logical commands such as
plus, minus, multiply, and divide.
• echo 6 + 2;
Arithmetic Operators
Assignment operators
• These operators are used to assign values to variables. They start with the very simple
= and move on to +=, −=, and so on
• Thus, if $count starts with the value 5, the statement:
$count += 1;
4.4
IT 3401 WEB ESSENTIALS UNIT 4
Comparison Operators
Logical Operators
Example
if ($hour > 12 && $hour < 14) dolunch();
4.5
IT 3401 WEB ESSENTIALS UNIT 4
• Variable Assignment
The syntax to assign a value to a variable is always variable = value. Or, to reassign the value
to another variable, it is other variable = variable.
There are also a couple of other assignment operators that you will find useful. For example,
we’ve already seen:
$x += 10;
which tells the PHP parser to add the value on the right (in this instance, the value 10) to the
variable $x. Likewise, we could subtract as follows:
$y −= 10;
• Adding or subtracting 1 is such a common operation that PHP provides special
operators for it. You can use one of the following in place of the += and −= operators:
++$x;
−−$y;
• In conjunction with a test (an if statement), you could use the following code:
• if (++$x == 10) echo $x;
• This tells PHP to first increment the value of $x and then test whether it has the value
10; if it does, output its value. But you can also require PHP to increment (or, in the
following example, decrement) a variable after it has tested the value, like this:
• if ($y−− == 0) echo $y;
String concatenation
• String concatenation uses the period (.) to append one string of characters to another.
• The simplest way to do this is as follows:
echo "You have " . $msgs . " messages.";
4.6
IT 3401 WEB ESSENTIALS UNIT 4
• Assuming that the variable $msgs is set to the value 5, the output from this line of
code will be:
You have 5 messages.
• Just as you can add a value to a numeric variable with the += operator, you can
append one string to another using .= like this:
$bulletin .= $newsflash;
• Escaping characters
• Sometimes a string needs to contain characters with special meanings that might be
interpreted incorrectly.
• $text = 'My spelling's atroshus'; // Erroneous syntax
• To correct this, you can add a backslash directly before the offending quotation
mark to tell PHP to treat the character literally and not to interpret it:
$text = 'My spelling\'s still atroshus';
Variable Typing
• PHP is a very loosely typed language. This means that variables do not have to be
declared before they are used .
• PHP always converts variables to the type required by their context when they are
accessed.
Automatic conversion from a number to a string
• <?php
• $number = 12345 * 67890;
• echo substr($number, 3, 1);
• ?>
Automatically converting a string to a number
• <?php
• $pi = "3.1415927";
• $radius = 5;
• echo $pi * ($radius * $radius);
• ?>
4.2.3 Constants
• Constants are similar to variables, holding information to be accessed later. A
constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
4.7
IT 3401 WEB ESSENTIALS UNIT 4
• A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Predefined Constants
PHP comes ready-made with dozens of predefined constants.
Magic constant Description
LINE The current line number of the file.
FILE Thefullpath and filename of the file.
DIR The directory of the file.
FUNCTION The function name.
CLASS The class name.
METHOD The class method name.
NAMESPACE The name of the current namespace (case-sensitive).
when you need to insert a line of code to see whether the program flow reaches
it: echo "This is line " . LINE . " of file " . FILE ;
Create a PHP Constant
PHP constant can be create,
• Using the define() function.
• Using const keyword
Syntax
define(name, value, case-insensitive)
Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
Example
1)
<?php
define("MESSAGE",“Welcome IT");
echo MESSAGE;
?>
4.8
IT 3401 WEB ESSENTIALS UNIT 4
2)
<?php
define("MESSAGE",“Welcome IT“,true);
echo MESSAGE;
Echo message;
?>
4.9
IT 3401 WEB ESSENTIALS UNIT 4
4.10
IT 3401 WEB ESSENTIALS UNIT 4
?>
elseif Statement
An if ... elseif ... else statement with curly braces
<?php
if ($bank_balance < 100)
{
$money = 1000;
$bank_balance += $money;
}
elseif ($bank_balance > 200)
{
$savings += 100;
$bank_balance −= 100;
}
else
{
$savings += 50;
$bank_balance −= 50;
}
?>
Switch Statement
<?php
switch ($page)
{
case "Home":
echo "You selected Home";
break;
case "About":
echo "You selected About";
break;
4.11
IT 3401 WEB ESSENTIALS UNIT 4
case "News":
echo "You selected News";
break;
case "Login":
echo "You selected Login";
break;
case "Links":
echo "You selected Links";
break;
}?>
• The ? Operator
• The ? operator is passed an expression that it must evaluate, along with two
statements to execute: one for when the expression evaluates to TRUE, the other for
when it is FALSE.
Using the ? operator
<?php
echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";
?>
Looping Statement
• A while loop
<?php
$fuel = 10;
while ($fuel >
1)
{
echo "There's enough fuel";
}
?>
A while loop to print the 12 times table
<?php
$count = 1;
while ($count <= 12)
4.12
IT 3401 WEB ESSENTIALS UNIT 4
{
echo "$count times 12 is " . $count * 12 . "<br>";
++$count;
}
?>
• do ... while Loops
A do ... while loop for printing the times table for 12
<?php
$count = 1;
do
{
echo "$count times 12 is " . $count * 12 . "<br>";
++$count;
}
while ($count <= 12);
?>
for Loops
Outputting the times table for 12 from a for loop
<?php
for ($count = 1 ; $count <= 12 ; ++$count)
{
echo "$count times 12 is " . $count * 12;
echo “<br>";
}
?>
Break and continue
The break statement can also be used to jump out of a loop.
<?php
for ($x= 0;$x< 10;$x++)
{ if ($x== 4)
{ break;
}
4.13
IT 3401 WEB ESSENTIALS UNIT 4
4.14
IT 3401 WEB ESSENTIALS UNIT 4
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Example 3
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";
echo($paper);
?>
Adding items to an array and retrieving them
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
for ($j = 0 ; $j < 4 ; ++$j)
echo "$j: $paper[$j]<br>";
?>
PHP Associative Array
• Can reference the items in an array by name rather than by number.
• PHP allows you to associate name/label with each array elements in PHP using =>
symbol.
4.15
IT 3401 WEB ESSENTIALS UNIT 4
4.16
IT 3401 WEB ESSENTIALS UNIT 4
}
?>
Walking through an associative array using foreach ... as
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
The foreach ... as Loop | 135
foreach($paper as $item => $description)
echo "$item: $description<br>";
?>
Multidimensional Arrays
PHP - Two-dimensional Arrays
A two-dimensional array is an array of arrays.
Volvo 22 18
BMW 15 13
Saab 5 2
Land 17 15
Rover
4.17
IT 3401 WEB ESSENTIALS UNIT 4
4.18
IT 3401 WEB ESSENTIALS UNIT 4
• sort
• Sorting is so common that PHP provides a built-in function. In its simplest form, you
would use it like this:
sort($fred);
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
You can also sort an array in reverse order using the rsort function, like this:
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
Shuffle
There may be times when you need the elements of an array to be put in random order, such as
when you’re creating a game of playing cards: shuffle($cards);
Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE
on error.
Explode
to split up a sentence into an array containing all its words.
Functions
• Some of the built-in functions that use one or more arguments.
Three string functions
<?php
echo strrev(" .dlrow olleH"); // Reverse string
echo str_repeat("Hip ", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase
?>
• This example uses three string functions to output the following text:
Hello world. Hip Hip HOORAY!
PHP User Defined Functions
• Besides the built-in PHP functions, it is possible to create your own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
4.19
IT 3401 WEB ESSENTIALS UNIT 4
<!DOCTYPE html>
<html>
<body>
<?php
function add($a,$b)
{
echo $a+$b;
}
add(12,34)
4.20
IT 3401 WEB ESSENTIALS UNIT 4
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function add($a,$b)
{ return $a+$b;
}
echo add(12,23);
?>
</body>
</html>
• Returning an Array
There are also ways of getting multiple values from a function.
The first method is to return them within an array. You can use an array to return function
values.
Returning multiple values in an array
4.21
IT 3401 WEB ESSENTIALS UNIT 4
<?php
$names = fix_names("WILLIAM", "henry",
"gatES"); echo $names[0] . " " . $names[1] . " " .
$names[2]; function fix_names($n1, $n2, $n3)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
return array($n1, $n2, $n3);
}
?>
Passing by Reference
• In PHP, prefacing a variable with the & symbol tells the parser to pass a reference to
the variable’s value, not the value itself.
<?php
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
fix_names($a1, $a2, $a3);
echo $a1 . " " . $a2 . " " . $a3;
function fix_names(&$n1, &$n2, &$n3)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
}
?>
• Returning Global Variables
• can also give a function access to an externally created variable by declaring it a
global variable from within the function.
<?php
4.22
IT 3401 WEB ESSENTIALS UNIT 4
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
fix_names();
echo $a1 . " " . $a2 . " " . $a3;
function fix_names()
{
global $a1,$a2,$a3;
$a1 = ucfirst(strtolower($a1));
$a2 = ucfirst(strtolower($a2));
$a3 = ucfirst(strtolower($a3));
}
?>
• A string is a sequence of characters, like "Hello world!".
4.2.7 PHP String Functions
strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
• str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
strrev() - Reverse a String
The PHP strrev() function reverses a string.
4.23
IT 3401 WEB ESSENTIALS UNIT 4
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
4.3 FILE HANDLING
Checking Whether a File Exists
• To determine whether a file already exists, you can use the file_exists function, which
returns either TRUE or FALSE, and is used like this:
if (file_exists("testfile.txt"))
echo "File exists";
• PHP readfile() Function
The readfile() function reads a file and writes it to the output buffer.
<html>
<body>
4.24
IT 3401 WEB ESSENTIALS UNIT 4
<?php
echo readfile("webexample.txt");
?>
</body>
</html>
PHP Open File - fopen()
• A better method to open files is with the fopen() function.
• The first parameter of fopen() contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened.
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
4.25
IT 3401 WEB ESSENTIALS UNIT 4
The fclose() requires the name of the file (or a variable that holds the filename) we want to
close:
<?php
$myfile = fopen("webexample.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); while(!
feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
4.26
IT 3401 WEB ESSENTIALS UNIT 4
The example below reads the "webdictionary.txt" file character by character, until end-of-file
is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
• Copying Files
Let’s try out the PHP copy function to create a clone of testfile.txt. <?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>
4.4 FILE UPLOADING
• PHP allows you to upload single and multiple files through few lines of code only.
PHP $_FILES
• The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated
with file.
Here, we are assuming that file name is filename.
• $_FILES['filename']['name’]
returns file name.
• $_FILES['filename']['type’]
returns MIME type of the file.
• $_FILES['filename']['size’]
returns size of the file (in bytes).
• $_FILES['filename']['tmp_name’]
returns temporary file name of the file which was stored on the server.
4.27
IT 3401 WEB ESSENTIALS UNIT 4
• $_FILES['filename']['error’]
returns error code associated with this file.
basename()
The basename() function returns the filename from a path.
Syntax
basename(string $filename , suffix)
basename( $_FILES['fileToUpload']['name']);
move_uploaded_file() function
• The move_uploaded_file() function moves the uploaded file to a new
location. Syntax
bool move_uploaded_file ( string $filename , string $destination )
<?php
$target_path = "e:/";
$target_path = $target_path.basename($_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
<form action="uploader.php" method="post“>
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
PHP and HTML
• When it comes to integrating PHP code with HTML content, you need to enclose the
PHP code with the PHP start tag <?php and the PHP end tag ?>.
• The code wrapped between these two tags is considered to be PHP code, and thus it'll
be executed on the server side before the requested file is sent to the client browser.
4.28
IT 3401 WEB ESSENTIALS UNIT 4
The overall structure of the PHP page combined with HTML and PHP code should look like
this:
<!DOCTYPE html>
<html>
<head>
<title>...</title>
</head>
<body>
HTML...
<?php PHP code ... ?>
HTML...
<?php PHP code ... ?>
HTML...
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - Simple Example</title>
</head>
<body>
<h1><?php echo "This message is from server side." ?></h1>
</body>
</html>
• This will output the current date and time, so you can use PHP code between the
HTML tags to produce dynamic output from the server.
• It’s important to remember that whenever the page is executed on the server side, all
the code between the <?php and ?> tags will be interpreted as PHP, and the output
will be embedded with the HTML tags.
<html>
4.29
IT 3401 WEB ESSENTIALS UNIT 4
<head>
<title>How to put PHP in HTML- Date Example</title>
</head>
<body>
<div>This is pure HTML message.</div>
<div>Next, we’ll display today’s date and day by PHP!</div>
<div>
<?php
echo 'Today’s date is <b>' . date('Y/m/d') . '</b> and it’s a <b>'.date('l').'</b> today!';
?>
</div>
<div>Again, this is static HTML content.</div>
</body>
</html>
Embedding HTML into PHP
<?php
echo "<html>\n";
echo "<head>\n";
echo "<title>My Second PHP Example</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<p>Some Content</p>\n";
echo "</body>\n";
echo "</html>\n";
?>
4.5 E-Mail Basics
• PHP makes use of mail() function to send an email.
• This function requires three mandatory arguments that specify the recipient's email
address, the subject of the message and the actual message additionally there are other
two optional parameters.
mail( to, subject, message, headers, parameters );
4.30
IT 3401 WEB ESSENTIALS UNIT 4
Sending email
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";
4.31
IT 3401 WEB ESSENTIALS UNIT 4
4.32
IT 3401 WEB ESSENTIALS UNIT 4
4.33
IT 3401 WEB ESSENTIALS UNIT 4
<?php
echo '<p>This is a PHP script</p>';
?>
<?php
phpInfo();
?>
This PHP script calls the built-in PHP phpInfo() function, the purpose of which to
output information about the PHP pre-processing module integrated into your web
server.
Save this file as phpInfo.php and upload it to a location on your web server where it
will be accessible via a web browser.
Once you have done this open a browser and go to the URL for this file. If all is well
with your PHP installation you will see several pages of detailed information about
your PHP environment covering topics such as how and when the PHP module was
built, the version of the module and numerous configuration settings.
If you do not see this information it is possible you do not have the PHP module
integrated into your web server. If you use a web hosting company, check with them
to see if your particular hosting package includes PHP support (sometimes PHP
support is only provided with premium hosting packages so you may need to
upgrade). If you run your own web server consult the documentation for your
particular type of server (Apache, Microsoft IIS etc) for details on integrating the PHP
module.
A healthy PHP installation should result in output similar to the following:
<html>
4.34
IT 3401 WEB ESSENTIALS UNIT 4
<head>
<?php
echo '<title>My First PHP Script</title>';
?>
</head>
<body>
<?php
echo '<p>This content was generated by PHP</p>';
?>
<p>And this content is static HTML</p>
</body>
</html>
<?php
echo "<html>\n";
echo "<head>\n";
echo "<title>My Second PHP Example</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<p>Some Content</p>\n";
echo "</body>\n";
echo "</html>\n";
?>
When you load this into your browser it will be as if all that was in the file was HTML, and if
you use the view page source feature of your browser the HTML is, infact, all you will see.
This is because the PHP pre-processor simply created the HTML it was told to create when it
executed the script:
<html>
<head>
<title>My Second PHP Example</title>
</head>
4.35
IT 3401 WEB ESSENTIALS UNIT 4
<body>
<p>Some Content</p>
</body>
</html>
MySQL
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported
by Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and
rows.
MySQL is a database system that runs on a server.
MySQL is ideal for both small and large applications.
MySQL is very fast, reliable, and easy to use database system.It uses standard
SQL
MySQL compiles on a number of platforms.
Downloading MySQL Database
MySQL can be downloaded for free from this link.
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension.
2. PDO (PHP Data Objects).
4.36
IT 3401 WEB ESSENTIALS UNIT 4
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Explanation: We can create an instance of the mysqli class providing all the necessary
details required to establish the connection such as host, username, password etc. If the
instance is created successfully then the connection is successful otherwise there is some
error in establishing connection.
Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to
establish a connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output:
Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the
information as arguments such as host, username , password , database name etc. This
4.37
IT 3401 WEB ESSENTIALS UNIT 4
function returns MySQL link identifier on successful connection or FALSE when failed to
establish a connection.
Using PDO procedure: PDO stands for PHP Data Objects. That is, in this
method we connect to the database using data objects in PHP as described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Output:
Explanation:The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.
Closing A Connection
When we establish a connection to MySQL database from a PHP script , we should also
disconnect or close the connection when our work is finished. Here we have described the
syntax of closing the connection to a MySQL database in all 3 methods described above. We
have assumed that the reference to the connection is stored in $conn variable.
Using MySQLi object oriented procedure
Syntax
$conn->close();
Using MySQLi procedural procedure
Syntax
mysqli_close($conn);
Using PDO procedure
Syntax
$conn = null;
PART A
4.38
IT 3401 WEB ESSENTIALS UNIT 4
PART A
1) Define PHP
Variable names must start with a letter of the alphabet or the _ (underscore) character.
• Variable names can contain only the characters a–z, A–Z, 0–9, and _ (underscore).
• Variable names may not contain spaces. If a variable must comprise more than
one word, it should be separated with the _ (underscore) character (e.g.,
$user_name).
• Variable names are case-sensitive. The variable $High_Score is not the same as
the variable $high_score.
4) How to define assignment operators
• These operators are used to assign values to variables. They start with the very simple
= and move on to +=, −=, and so on
• Thus, if $count starts with the value 5, the statement:
o $count += 1;
5) Write one example for string concatenation.
• String concatenation uses the period (.) to append one string of characters to
another.
• The simplest way to do this is as follows:
echo "You have " . $msgs . " messages.";
• Assuming that the variable $msgs is set to the value 5, the output from this line of
code will be:
You have 5 messages.
4.39
IT 3401 WEB ESSENTIALS UNIT 4
• Just as you can add a value to a numeric variable with the += operator, you can
append one string to another using .= like this:
$bulletin .= $newsflash;
6) Write two method for creating PHP constant.
• The ? operator is passed an expression that it must evaluate, along with two
statements to execute: one for when the expression evaluates to TRUE, the other for
when it is FALSE.
9) List possible data types available in PHP.
4.40
IT 3401 WEB ESSENTIALS UNIT 4
11) Write the uses of text manipulation with regular expression in PHP.
PHP processes text data easily and efficiently, enabling straightforward searching,
substitution, extraction and concatenation of strings.
Text manipulation in PHP is usually done with regular expressions — a series of
characters that serve as pattern-matching templates (or search criteria) in strings, text
files and databases.
This feature allows complex searching and string processing to be performed using
relatively simple expressions
12) How to Include PHP in a Web Page?
There are 4 ways of including PHP in a web page
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
13) Write a simple PHP script
Here is PHP script which is embedded in HTML using level one header with the
PHP output text. The name of this file is called hello.php.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
PART B
1) Write the working principle of PHP
PART C
1) Write a program for classroom management system using database and arrays.
4.41