unit-v-php-mc4023-web-design-lecture-notes
unit-v-php-mc4023-web-design-lecture-notes
Single Line Comment: As the name suggests these are single line or short
relevant explanations that one can add to their code. To add this, we need to
begin the line with (//) or (#).
Multi-line or Multiple line Comment: These are used to accommodate multiple
lines with a single tag and can be extended to many lines as required by the user.
To add this, we need to begin and end the line with (/*…*/)
PHP is case-sensitive. All the keywords, functions, and class names in PHP (while, if, echo,
else, etc) are NOT case-sensitive except variables. Only variables with different cases are
treated differently.
EX:
<?php
// Here we can see that all echo
// statements are executed in the same manner
$variable = 25;
echo $variable;
ECHO $variable;
EcHo $variable;
Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric values,
memory addresses, and strings. PHP has its own way of declaring and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while
dealing with variables in PHP:
Any variables declared in PHP must begin with a dollar sign ($), followed by the
variable name.
A variable can have long descriptive names (like $factorial, $even_nos) or short
names (like $n or $f or $x)
A variable name can only contain alphanumeric characters and underscores (i.e.,
‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name. Even it cannot start with a number.
A constant is used as a variable for a simple value that cannot be changed. It is
also case-sensitive.
Assignment of variables is done with the assignment operator, “equal to (=)”. The
variable names are on the left of equal and the expression or values are to the right
of the assignment operator ‘=’.
One must keep in mind that variable names in PHP names must start with a letter
or underscore and no numbers.
PHP is a loosely typed language, and we do not require to declare the data types
of variables, rather PHP assumes it automatically by analyzing the values. The
same happens while conversion. No variables are declared before they are used. It
automatically converts types from one type to another whenever required.
PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
Data types used by PHP to declare or construct variables:
Integers
Doubles
NULL
Strings
Booleans
Arrays
Objects
Resources
Example:
PHP
<?php
?>
Local variables: The variables declared within a function are called local variables to that
function and has its scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with same
name as that of the one within the function is a complete different variable.
Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function
we need to use the “global” keyword before the variable to refer to the global variable.
Forms are used to get input from the user and submit it to the web server for processing.
A form is an HTML tag that contains graphical user interface items such as input box, check
boxes radio buttons etc.
The form is defined using the <form>…</form> tags and GUI items are defined using form
elements such as input.
Forms come in handy when developing flexible and dynamic applications that accept
user input.
Forms can be used to edit already existing data from the database
Create a form
We will use HTML tags to create a form. Below is the minimal list of things you need to
create a form.
<html>
<head>
<title>Registration Form</title>
<h2>Registration Form</h2>
</form>
</body>
</html>
Viewing the above code in a web browser displays the following form.
HERE,
This is the built in PHP super global array variable that is used to get values submitted
via HTTP POST method.
The array variable can be accessed from any script in the program; it has a global
scope.
This method is ideal when you do not want to display the form post values in the
URL.
A good example of using post method is when submitting login details to the server.
<?php
$_POST['variable_name'];
?>
HERE,
This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method.
The array variable can be accessed from any script in the program; it has a global
scope.
This method displays the form values in the URL.
It’s ideal for search engine forms as it allows the users to book mark the results.
<?php
$_GET['variable_name'];
?>
HERE,
2. Has not limitation of the length of the Has limitation on the length of the values usually 255
values since they are submitted via the characters. This is because the values are displayed in
body of HTTP the URL. Note the upper limit of the characters is
dependent on the browser.
3. Has lower performance compared to Has high performance compared to POST method
Php_GET method due to time spent dues to the simple nature of appending the values in
encapsulation the Php_POST values in the URL.
the HTTP body
4. Supports many different data types Supports only string data types because the values are
such as string, numeric, binary etc. displayed in the URL
5. Results cannot be book marked Results can be book marked due to the visibility of
the values in the URL
The below diagram shows the difference between get and post
<?php
$file = fopen(“demo.txt”,'w');
?>
<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
3) fwrite() – New file can be created or text can be appended to an existing file using
fwrite() function. Arguments for fwrite() function are file pointer and text that is to written
to file. It can contain optional third argument where length of text to written is specified,
e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be
closed, e.g.,
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that the site can
retrieve to personalize the page when the user visits the website next time. A cookie can only be read
from the domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript
can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie will not be
set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
Security: It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury
Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip an
argument, the argument can be replaced by an empty string(“”).
Output:
Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a
cookie, the setcookie() function is called by passing the cookie name and other arguments
or empty strings but however this time, the expiration date is required to be set in the past.
To delete a cookie named “Auction_Item”, the following code can be executed.
PHP | Sessions
What is a session?
In general, session refers to a frame of communication between two medium. A PHP session
is used to store data on a server rather than the computer of the user. Session identifiers or SID
is a unique number which is used to identify every user in a session based environment. The
SID is used to link the user with his information on the server like posts, emails etc
Although cookies are also used for storing user related data, they have serious security
issues because cookies are stored on the user’s computer and thus they are open to attackers
to easily modify the content of the cookie.Addition of harmful data by the attackers in the
cookie may result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data each
time the user views a page.Every time the browser requests a URL to the server, all the cookie
data for that website is automatically sent to the server within the request.
<?php
session_start();
?>
<?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
<?php
session_start();
?>
Output:
The Name of the student is :Ajay
The Roll number of the student is :11
Destroying Certain Session Data: To delete only a certain session data,the
unset feature can be used with the corresponding session variable in
the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>
What Is WAMP
WAMP is an acronym that stands for Windows, Apache, MySQL, and PHP. It’s a software
stack which means installing WAMP installs Apache, MySQL, and PHP on your operating system
(Windows in the case of WAMP). Even though you can install them separately, they are usually
Let me explain today how to use the wamp server to run the PHP files. First of all download the Latest
wamp server from here:
http://www.wampserver.com/
and install the server.
Step 2:
Run wamp server by this selction
start->All programs->Wamp server->Start wamp server
Note: while saving the file, end the name with .php and don’t forget to select all files.
Let us assume i have stored Testing.php
Step 4: Start the server
Left click on the wamp icon in system tray.
It will display list of options.
Select “start all services”.
Step 5:Run
Now all services(especially php) is running.
Open the mozilla and type localhost in address bar.
Hit enter
It will show the default page of wamp server.
Now include this Testing.php (my php file name) at the end of the url
For ex:
http://localhost/Testing.php
It will run your php file.
It is the most popular application for MySQL database management. We can create, update, drop,
alter, delete, import, and export MySQL database tables by using this software. phpMyAdmin also supports
a wide range of operation like managing databases, relations, tables, columns, indexes, permissions,
and users, etc., on MySQL and MariaDB. These operations can be performed via user interface, while we
still have the ability to execute any SQL statement.
phpMyAdmin is translated into 72 languages and also supports both RTL and LTR languages so
that the wide range of people can easily use this software. We can run MySQL queries, repair, optimized,
check tables, and also execute other database management commands. phpMyAdmin can also be used to
perform administrative tasks such as database creation, query execution.
Features of phpMyAdmin
o phpMyAdmin can create, alter, browse, and drop databases, views, tables, columns, and indexes.
o It can display multiple results sets through queries and stored procedures.
o phpMyAdmin use stored procedure and queries to display multiple results sets.
o It supports foreign keys and InnoDB tables.
o phpMyAdmin can track the changes done on databases, views, and tables.
o We can also create PDF graphics of our database layout.
o phpMyAdmin can be exported into various formats such as XML, CSV, PDF, ISO/IEC 26300 -
OpenDocument Text and Spreadsheet.
o It supports mysqli, which is the improved MySQL extension.
o phpMyAdmin can interact with 80 different languages.
o phpMyAdmin can edit, execute, and bookmark any SQL-statements and even batch-queries.
o By using a set of pre-defined functions, it can transform stored data into any format. For example -
BLOB-data as image or download-link.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 15
Advantage of phpMyAdmin
o phpMyAdmin can run on any server or any OS as it has a web browser.
o We can easily create, delete, and edit the database and can manage all elements using the graphical
interface of phpMyAdmin, which is much easier than MySQL command-line editor.
o phpMyAdmin helps us to control the user's permission and operate several servers at the same time.
o We can also backup our database and export the data into different formats like XML, CSV, SQL,
PDF, OpenDocument Text, Excel, Word, and Spreadsheet, etc.
o We can execute complex SQL statements and queries, create and edit functions, triggers, and events
using the graphical interface of phpMyAdmin.
Disadvantage of phpMyAdmin
o phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
o phpMyAdmin is difficult to install as it needs three more software tools before installation, which is-
Apache server, PHP, and MySQL.
o We have to install all these software tools individually, whereas XAMPP already contains them in a
single package. XAMPP is the easiest way to get phpMyAdmin.
o It has no schema visualization.
o phpMyAdmin is a web-based software tool which runs only on the browser, so It completely
depends on browsers.
o It does not have auto-compilation capability.
Introduction
To access and add content to a MySQL database, you must first establish a connection between the
database and a PHP script.
Prerequisites
There are two popular ways to connect to a MySQL database using PHP:
The guide also includes explanations for the credentials used in the PHP scripts and potential errors you
may come across using MySQLi and PDO.
MySQLi is an extension that only supports MySQL databases. It allows access to new functionalities found
in MySQL systems (version 4.1. and above), providing both an object-oriented and procedural interface. It
supports server-side prepared statements, but not client-side prepared statements.
The PHP script for connecting to a MySQL database using the MySQLi procedural approach is the
following:
<?php
$servername = "localhost";
$database = "database";
$username = "username";
$password = "password";
// Create connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_close($conn);
?>
Credentials Explained
The first part of the script is four variables (server name, database, username, and password) and their
respective values. These values should correspond to your connection details.
Next is the main PHP function mysqli_connect(). It establishes a connection with the specified database.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 17
Following is an “if statement.” It is the part of the code that shows whether the connection was established.
When the connection fails, it gives the message Connection failed. The die function prints the message and
then exits out of the script.
When the script ends, the connection with the database also closes. If you want to end the code manually,
use the mysqli_close function.
PHP Data Objects (PDO) is an extension that serves as an interface for connecting to databases. Unlike
MySQLi, it can perform any database functions and is not limited to MySQL. It allows flexibility among
databases and is more general than MySQL. PDO supports both server and client-side prepared statements.
Note: PDO will not run on PHP versions older than 5.0 and is included in PHP 5.1.
The PHP code for connecting to a MySQL database through the PDO extension is:
<?php
$servername = "localhost";
$database = "database";
$username = "username";
$password = "password";
$charset = "utf8mb4";
try {
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo
{
echo “Connection failed: ”. $e->getMessage();
}
?>
Credentials Syntax
First, we have five variables (server name, database, username, password, and charset) and their values.
These values should correspond to your connection details.
The server name will be localhost. If connected to an online server, type in the server name of that server.
The variable charset tells the database in which encoding it will be receiving and sending data. The
recommended standard is utf8mb4.
PDO’s great asset is that it has an exception class to take care of any potential problems in database queries.
It solves these problems by incorporating try and catch blocks.
If a problem arises while trying to connect, it stops running and attempts to catch and solve the
issue. Catch blocks can be set to show error messages or run an alternative code.
The first parameter in the try and catch block is DSN, which stands for data(base) source name. It is
crucial as it defines the type and name of the database, along with any other additional information.
In this example, we are using a MySQL database. However, PDO supports various types of databases. If
you have a different database, replace that part of the syntax (mysql) with the database you are using.
Next is the PDO variable. This variable is going to establish a connection to the database. It has three
parameters:
1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION
This method instructs the PDO to run an exception in case a query fails.
After returning the PDO variable, define the PDOException in the catch block by instructing it to display a
message when the connection fails.
The password in the PHP code needs to correspond with the one in the database. If the two do not match, a
connection with the database cannot be established. You will receive an error message saying the
connection has failed.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 20
Possible solutions:
PHP may not be able to connect to the MySQL server if the server name is not recognized. Make sure that
the server name is set to localhost.
In case of other errors, make sure to consult the error_log file to help when trying to solve any issues. The
file is located in the same folder where the script is running.