Course Code: DSC17
Course Title: PHP and MySQL
Credits - 04
Sem - VI
Hours- 52
Formative Assessment Marks: 40
Summative Assessment Marks: 60
Duration of SEA/Exam: 02 hrs.
Course Outcomes (COs): After the successful completion of the course, the
student will be able to:
1. Design dynamic and interactive web pages and websites.
2. Run PHP scripts on the server and retrieve results.
3. Handle databases like MySQL using PHP in websites.
Contents 52 Hrs
Unit I 10 Hrs
Introduction: -Introduction to PHP, History and Features of PHP, Installation &
Configuration of PHP, Embedding PHP code in your web pages, Understanding
PHP,HTML and white space, Writing comments in PHP, Sending data to the web
browser, Data types in PHP, Keywords in PHP, using variables, constants in PHP,
expressions in PHP, operators in PHP.
Unit II 12 Hrs
Programming with PHP: - Conditional statements: If, if-else, switch, The?
Operator, Looping statements: While Loop, do-while Loop, for Loop, Arrays in
PHP: Introduction-What is array?, Creating Arrays, Accessing array elements,
Types of arrays: Indexed v/s Associative arrays, Multidimensional arrays,
Creating array, Accessing array, Manipulating Arrays, Displaying array, using
array functions, Including and requiring files-use of Include() and
Require(),Implicit and Explicit casting in PHP.
Unit III 10 Hrs
Using Functions, class- objects, Forms in PHP: - Functions in PHP, Function
definition, Creating and invoking user-defined functions, Formal parameters
versus actual parameters, Function and variable scope, Recursion, Library
functions, Date and time functions, strings in PHP: What is string?, Creating And
declaring string, String functions.
Unit IV 10 Hrs
Class & objects in PHP: - What is class & object, Creating and accessing a class &
object, Object properties, Object methods, Overloading, inheritance, constructor
and destructor, form handling: Creating HTML form, Handling HTML form data in
PHP.
Unit V 10 Hrs
Database Handling using PHP with MySQL: - Introduction to MySQL: Database
terms, Data types, Accessing MySQL- Using MySQL Client and using PHP
MyAdmin, MySQL commands, using PHP with MySQL: PHP MySQL functions,
connecting to MySQL and selecting the database, Executing simple Queries,
Retrieving query results, Counting returned records, Updating records with PHP.
Unit 1
Introduction to PHP
PHP
PHP is the Web development language written by and for Web developers.
PHP stands for PHP: Hypertext Preprocessor. The product was
originally named Personal Home Page Tools.
PHP is a server-side scripting language, which can be embedded in
HTML or used as a standalone binary.
History and Features of PHP
History:
1. Creation (1994): Rasmus Lerdorf created PHP as a set of Perl
scripts for his personal use to manage his online resume and track
web visits.
2. PHP/FI (1995): Lerdorf extended his scripts and released the PHP/FI
(Personal Home Page/Forms Interpreter) version, which added the
ability to create simple dynamic web applications.
3. PHP 3 (1998): The first formal version of PHP was released,
introducing a more robust and modular architecture.
4. PHP 4 (2000): This version brought significant improvements and
features such as better support for object-oriented programming (OOP)
and introduced the Zend Engine, which greatly enhanced PHP's
performance.
5. PHP 5 (2004): PHP 5 further improved support for OOP with features like
interfaces and exceptions. It also introduced the Standard PHP Library
(SPL) and enhanced XML support.
6. PHP 6 (Development halted): Work began on PHP 6 to add native Unicode
support. However, due to technical challenges and delays, the project
was eventually abandoned.
7. PHP 7 (2015): PHP 7 was a major release known for its significant
performance improvements, with up to twice the speed of PHP 5. PHP
7 also introduced many new features and enhancements, including
scalar type declarations, return type declarations, anonymous classes,
and more.
8. PHP 8 (2020): PHP 8 brought several new features and improvements,
including Just-In-Time (JIT) compilation for improved performance,
union types, named arguments, attributes, and more.
Features:
1. Server-Side Scripting: PHP is primarily used for server-side scripting,
meaning that it runs on a web server and processes code before sending
the output to the client's browser. This allows for dynamic content
generation.
2. Dynamic Typing: PHP is dynamically typed, meaning you don’t need to
declare the data type of a variable explicitly.
3. Ease of Use: PHP syntax is relatively easy to learn and understand,
especially for beginners. It is similar to C, Java, and Perl, making it
accessible to developers from various programming backgrounds.
4. Wide Compatibility: PHP is compatible with most web servers and
operating systems, including Linux, Unix, Windows, macOS, and more. It
also supports a wide range of databases, including MySQL, PostgreSQL,
SQLite, and Oracle.
5. Support for Various Protocols: PHP supports various network
protocols, such as HTTP, SMTP, LDAP, IMAP, POP3, and more, making
it versatile for web development and beyond.
6. Extensive Library Support: PHP has a vast ecosystem of libraries and
frameworks, such as Laravel, Symfony, CodeIgniter, and WordPress,
which help developers build web applications more efficiently.
7. Embeddable: PHP code can be embedded directly into HTML, allowing
developers to mix dynamic content with static content seamlessly.
8. Open Source: PHP is open-source software, meaning it is freely available
for anyone to use, modify, and distribute.
9. Active Community: PHP has a large and active community of developers
who contribute to its development, provide support, and share resources
and knowledge.
Installation and Configuration of PHP
To start working with PHP, you need a local development environment.
This environment simulates a web server on your computer, allowing you
to test your PHP code before deploying it to a live server.
Popular choices for local server setups include XAMPP, WAMP, and MAMP.
These software packages come bundled with Apache (the web server),
MySQL (the database), and PHP, forming the core components for web
development.
Installing a Local Server
XAMPP: Download XAMPP from the official website, and follow the
installation instructions for your operating system. Once installed, you
can start the Apache and MySQL services from the control panel.
WAMP: Similarly, for Windows users, WAMP provides an easy installation
process. After installation, launch the WAMP control panel to start the
Apache and MySQL services.
MAMP: Mac users can opt for MAMP. After installation, you can
configure the Apache and MySQL settings through the MAMP
application.
Detailed guide on installing XAMPP for Windows
1. Downloading XAMPP
Visit the official XAMPP download
page: [Link]
Select the download corresponding to your operating system (Windows,
macOS, or Linux).
Choose either the installer or the archive (.zip) file.
2. Installing XAMPP
For Installer: Double-click the downloaded .exe file.
Follow the on-screen instructions in the XAMPP Setup Wizard.
Choose an installation directory (it's recommended to keep the default
suggested location, typically C:\xampp).
You can optionally select which components to install (Apache, MySQL,
PHP, etc.). By default, all components are selected.
Click "Next" and follow any further prompts until the installation is complete.
3. Starting and Stopping XAMPP Services
Open the XAMPP Control Panel by going to Start -> All Programs ->
XAMPP -> XAMPP Control Panel.
4. Verifying Installation
Open a web browser and navigate to [Link] You should see
the default XAMPP welcome page if everything is functioning
correctly.
Embedding PHP Code in your Web Pages
Embedding PHP code in web pages allows you to create dynamic content
by executing server-side scripts before sending the HTML to the client's
browser. Here's how you can embed PHP code in your web pages:
1. Using PHP Opening and Closing Tags:
PHP code is enclosed within opening <?php and closing ?> tags.
Any code within these tags will be interpreted and executed by the server.
<?php
// PHP code goes here
?>
2. Embedding PHP within HTML:
You can embed PHP code within HTML tags or anywhere in an HTML documen
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1>Today's Date</h1>
<p>
<?php
// PHP code to display today's date
echo "Today is " . date("Y-m-d") .
".";
?>
</p>
</body>
</html>
3. Using Short Tags
Short tags (<? ... ?>) can also be used to embed PHP code, but
they are not recommended for compatibility reasons and may be
disabled in some PHP configurations.
<?
// PHP code goes here
?>
4. Outputting HTML within PHP:
You can output HTML content within PHP using echo or print statements.
<?php
echo "<h1> ICCA </h1>";
?>
5. Embedding PHP in External Files:
PHP code can also be embedded in external files with a .php extension,
which are then included or required in other PHP scripts.
[Link]
<?php
$message = "Hello from external file!";
?>
[Link]
<!DOCTYPE html>
<html>
<head>
<title>External PHP Example</title>
</head>
<body>
<?php include '[Link]'; ?>
<p><?php echo $message; ?></p>
</body>
</html>
Understanding PHP,HTML and White Space
1. PHP and HTML Interaction:
PHP dynamically generates HTML content for web pages.
PHP generates HTML source code, which is then rendered by the web browser.
This interaction allows for the creation of dynamic and interactive web pages.
2. White Space Insensitivity:
PHP and HTML are generally insensitive to white space, allowing
developers to format code for better readability without affecting
functionality or rendering.
In PHP, developers can space out code and use blank lines for better organization.
In HTML, extraneous white spacing doesn't affect the appearance of
the rendered page, but it can improve the readability of the source
code.
3. Examples:
In PHP scripts, developers can format code across multiple lines
without affecting functionality.
<?php
echo "ICCA"; // Whitespaces can be used better readability
?>
In HTML source, different formatting styles will render the same page,
as HTML is mostly white space insensitive.
<html>
<head><title>HTML Code</title></head>
<body>
<?php echo "<h1>Welcome to ICCA</h1>";?>
</body>
</html>
4. Creating White Space:
Developers can use HTML tags like <br /> (line break) and <p></p>
(paragraph) to control spacing in the rendered web page.
In PHP, developers can use echo() or print() statements over multiple lines
or use the newline character (\n) within double quotation marks to control
white space in the generated HTML source.
Writing Comments in PHP
Adding comments to your PHP code is crucial for improving
readability, maintainability, and collaboration
Single-line comments: Use two forward slashes (//) followed by your
comment text. Everything after // on that line is ignored by the PHP
interpreter.
// This is a single-line comment explaining the code above.
Multi-line comments: Use the /* and */ symbols to enclose your
comment text. This allows comments to span multiple lines.
/*
This is a multi-line comment.
It can explain a complex code
block or provide additional
information.
*/
Sending Data to the web browser
In PHP, there are several ways to send data to the web browser. Here's an
overview of the common methods:
1. Using echo or print statements:
These are the simplest methods for sending data to the browser. They
directly output the provided string or variable value.
<?php
echo "ICCA";
print "<br> Interface College";
?>
2. HTML Output:
When working with PHP to generate dynamic web pages, you'll often
be sending HTML content. You can directly embed HTML code within
your PHP script using quotation marks.
<?php
echo "<h1>ICCA</h1>";
print "<h2> Interface College</h2>";
?>
3. Sending Arrays:
You can send arrays to the browser using print_r or var_dump for
debugging purposes.
<?php
$arrayele = array("Interface","College","of","Computer","Applications");
print_r($arrayele);
echo "<br>";
print_r( $arrayele[0
] ); echo "<br>";
var_dump( $arrayel
e ); echo "<br>";
var_dump( $arrayele[1] );
?>
4. Sending File Content:
You can send the content of a file to the browser using functions like
readfile or file_get_contents.
<?php
readfile("[Link]"
);
// or
echo file_get_contents("[Link]");
?>
5. Sending HTTP Headers:
You can send HTTP headers using the header function to control various
aspects of the response, such as content type or caching.
header("Content-Type: text/plain"); // Informs browser the content is
plain text. echo "This is plain text data.";
Data Types in PHP
Different types of data take up different amounts of memory and may
be treated differently when they are manipulated by a script.
PHP is loosely typed, meaning that it automatically determines the data
type at the time data is assigned to each variable.
Example
<?php
$a = 25; //Integer
$b = 12.25; //Float
$c = $a-$b;
$d =
"ICCA";//String
echo "$c<br/>";
echo "$d";
?>
Output
Note:
1) Resource types are often returned by functions that deal with external applications or files
2) The NULL type is reserved for variables that have been declared but no
value has been assigned to them.
Testing the Type of a Variable
PHP has several functions available to test the validity of a particular type
of variable one for each type
The is_* family of functions, such as
1. is_null () function is used to test whether a variable is NULL or not.
2. is_int() function is used to test whether the type of the specified variable
is an integer or not.
3. is_string() function is used to find whether a variable is a string or not
4. is_double() function is used to test whether a variable is a float/double
or not. The function
5. is an alias of is_float().
6. is_bool() function is used to find whether a variable is an a boolean or not.
7. is_array() function is used to find whether a variable is an array or not.
8. is_numeric() function is used to check whether a variable is numeric or not.
9. is_resource() function is used to find whether a variable is a resource or not.
Example
<?php
$testing = 5;
echo "is an integer? ".is_int($testing) ."<br/>";
$testing = "five";
echo "is a string? ".is_string($testing) ."<br/>";
$testing = 5.024;
echo "is a double? ".is_double($testing) ."<br/>";
$testing = true;
echo "is boolean? ".is_bool($testing) ."<br/>";
$testing = array('apple', 'orange', 'pear');
echo "is an array?
".is_array($testing) ."<br/>"; echo "is
numeric? ".is_numeric($testing) ."<br/>";
echo "is a resource? ".is_resource($testing)
."<br/>"; echo "is an array?
".is_array($testing) ."<br/>";
?>
Output
Keywords in PHP
PHP has a set of keywords that are reserved words which cannot
be used as function names, class names or method names.
Example: - class, function, new, global, goto, break, continue,include,extends etc….
Variables in PHP
A variable is a special container, which “holds” a value, such as a number,
string, object, array, or a Boolean.
Rules of for naming variable
A variable consists of a name of your choosing, preceded by a dollar sign($).
Variable names can include letters, numbers, and the underscore
character(_), but they cannot include spaces.
Names must begin with a letter or an underscore.
$a;
$a_longish_variable_name;
$2453;
$sleepyZZZZ;
Example
<?php
$a = 25; //Integer
$b = 12.25; //Float
$c = $a-$b;
$d = "ICCA";//String
echo "$c<br/>";
echo "$d";
?>
Globals and Superglobals Variables
1. Global Variables
In addition to the rules for naming variables, there are rules
regarding the availability of variables.
In general, the assigned value of a variable is present only within
the function or script where it resides.
For example, if you have [Link] that holds a variable called
$name with a value of joe, and you want to create [Link] that
also uses a $name variable, you can assign to that second $name
variable a value of john without affecting the variable in
[Link].
The value of the $name variable is local to each script, and the
assigned values are independent of each other.
However, you can also define the $name variable as global within
a script or function. If the $name variable is defined as a global
variable in both [Link] and [Link], and these scripts are
connected to each other (that is, one script calls the other or
includes the other), there will be just one value for the now-
shared $name variable.
2. Superglobal Variables
In addition to global variables of your own creation, PHP has
several predefined variables called superglobals.
These variables are always present, and their values are available
to all your scripts. Each of the following superglobals is actually an
array of other variables:
o $_GET contains any variables provided to a script through
the GET method.
o $_POST contains any variables provided to a script through
the POST method. $_COOKIE contains any variables provided
to a script through a cookie.
o $_FILES contains any variables provided to a script
through file uploads.
o $_SERVER contains information such as headers, file paths,
and script locations. $_ENV contains any variables provided
to a script as part of the server environment. $_REQUEST
contains any variables provided to a script via GET, POST, or
COOKIE input mechanisms.
o $_SESSION contains any variables that are currently
registered in a session.
Constant in PHP
The value does not change after the execution of the program is called constant.
You must use PHP’s built-in define() function to create a
constant, which subsequently cannot be changed unless you
specifically define() it again.
To use the define() function, place the name of the constant and the
value you want to give it within parentheses and separated by a comma:
Example
<?php
define("THE_YEAR", "2024");
echo "It is the year ".THE_YEAR;
?>
Output
The define() function can also accept a third Boolean argument that
determines whether the constant name should be case sensitive.
By default, constant names are case sensitive.
However, by passing true to the define() function, you can change this
behavior. you could access the “THE_YEAR” constant without worrying
about case:
eg: echo the_year;
echo ThE_YeAr;
echo THE_YEAR;
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do
not know its name, i.e. It is stored in a variable or returned by a function.
Example
<?php
define("THE_YEAR", "2024");
echo "It is the year ".THE_YEAR."<br/>";
echo constant("THE_YEAR");
?>
Output
Predefined Constants
PHP automatically provides some built-in constants for you.
For example, the constant FILE returns the name of the file that the PHP
engine is currently reading. The constant LINE returns the current line
number of the file.
Expression
An expression is any combination of functions, values, and operators that
resolves to a value
(OR)
The combination of operands with an operator to produce a result is
called an expression
Eg: a + b; Where: a & b are operands + is a operator
Operators in PHP
Operators are symbols used to manipulate data stored in variables, to
make it possible to use one or more values to produce a new value, or to
check the validity of data to determine the next step in a condition, and so
forth
1. Arithmetic Operators: - There are following arithmetic operators
supported by PHP language.
2. The Assignment Operator
o The assignment operator consists of the single character: =.
o The assignment operator takes the value of the right-side
operand and assigns it to the left-side operand
o Example: $name = “Jimbo”;
3. Combined Assignment Operators
o A combined assignment operator consists of a standard
operator symbol followed by an equal sign.
o Each arithmetic operator, as well as the concatenation operator,
also has a corresponding combination assignment operator.
4. Comparison Operators
o Comparison operators perform comparative tests using their
operands and return the Boolean value true if the test is
successful or false if the test fails.
Example:
(1) $x=5; (2) $x=5;
$y=5.0; $y=5.0;
$x= = $y // returns true $x= = = $y // returns false
5. Increment & Decrement Operator
o PHP provides some special operators that allow you to add or
subtract the integer constant 1 from an integer variable, assigning
the result to the variable itself.
1. Post- increment & decrement operator
$x++; $x is incremented by 1
$x- - ; $x is decremented by 1
2. Pre- increment and decrement operator
++$x; $x is incremented by 1
- -$x ; $x is decremented by 1
6. Logical Operator
o Logical operators test combinations of Boolean values.
o For example, the or operator, which is indicated by two pipe
characters (||) or simply the word or, returns the Boolean value
7. The Concatenation Operator
o The concatenation operator is represented by a single period (.).
o Treating both operands as strings, this operator appends the
right-side operand to the left- side operand.
o So “hello”.” world” returns “hello world”
Operator precedence
Operator precedence determines the grouping of terms in an expression.
This affects how an expression is evaluated.
Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence
than the addition operator
Example
<?php
$num1 = 100;
$num2 = 200;
$num3 = 90;
if(( $num1 > $num2 ) && ($num1>$num3))
{
echo "$num1 is greater";
}
elseif( $num2 > $num3 )
{
echo"$num2 is greater";
}
else
{
echo"$num3 is greater";
}
?
>
Output